How to use zig build for importing C++23's std?

I referred to the links you provided and got it working with cmake. Thanks a lot !


Importing the std module

Using clang

The CMakeLists.txt file looks like:

cmake_minimum_required(VERSION 3.31)

# https://libcxx.llvm.org/Modules.html
set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "0e5b6991-d74f-4b3d-a41c-cf096e0b2508")
set(CMAKE_CXX_MODULE_STD ON)
set(CXXFLAGS "-stdlib=libc++")
set(CMAKE_CXX_FLAGS "${CXXFLAGS}")
set(CMAKE_CXX_COMPILER clang++)

project("example"
  LANGUAGES CXX
)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
# Currently CMake requires extensions enabled when using import std.
# https://gitlab.kitware.com/cmake/cmake/-/issues/25916
# https://gitlab.kitware.com/cmake/cmake/-/issues/25539
set(CMAKE_CXX_EXTENSIONS ON)

add_executable(main)
target_sources(main
  PRIVATE
  src/main.cpp
)

and src/main.cpp:

import std;

int main() {
    int answer { 42 };
    std::println("The answer to life, the universe, and everything is {}.", answer);
    return 0;
}

which can be executed with:

  • cmake -G Ninja -S . -B build

  • ninja -C build

  • ./build/main

1 Like