CMake 具有实验性 C++20 模块依赖扫描 ( !5562 )。我尝试使用 CMake 3.20、g++-11 和 ninja-1.10 来构建带有模块的项目。
// main.cpp
import mod;
int main() { return 0; }
// mod.ixx
export module mod;
export void f() {}
CMakeLists.txt 改编自https://gitlab.kitware.com/ben.boeckel/cmake/blob/cpp-modules/Modules/Compiler/GNU-CXX.cmake
cmake_minimum_required(VERSION 3.20)
project(simple)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_DEPFILE_FORMAT gcc)
set(CMAKE_CXX_DEPENDS_USE_COMPILER TRUE)
string(CONCAT CMAKE_EXPERIMENTAL_CXX_SCANDEP_SOURCE
"<CMAKE_CXX_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E -x c++ <SOURCE>"
" -MT <DYNDEP_FILE> -MD -MF <DEP_FILE>"
" -fmodules-ts -fdep-file=<DYNDEP_FILE> -fdep-output=<OBJECT>"
" -fdep-format=trtbd")
set(CMAKE_EXPERIMENTAL_CXX_MODULE_MAP_FORMAT "gcc")
set(CMAKE_EXPERIMENTAL_CXX_MODULE_MAP_FLAG
" -fmodules-ts -fmodule-mapper=<MODULE_MAP_FILE>"
" -fdep-format=trtbd -x c++")
set(CMAKE_CXX_FLAGS "-fmodules-ts")
add_executable(simple main.cpp mod.ixx)
但是 CMake 和 ninja 不构建项目:
$ mkdir build && cd build
$ cmake -DCMAKE_CXX_COMPILER=<path to g++-11>/g++-11 -G Ninja ..
-- The C compiler identification is GNU 10.3.1
-- The CXX compiler identification is GNU 11.1.0
-- Detecting C compiler ABI info
...
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: <...>
$ ninja
<...>/g++-11 -fmodules-ts -std=gnu++20 -MD -MT <...>/main.cpp.o
-MF <...>/main.cpp.o.d -o <...>/main.cpp.o -c ../main.cpp
In module imported at ../main.cpp:1:1:
mod: error: failed to read compiled module: No such file or directory
mod: note: compiled module file is ‘gcm.cache/mod.gcm’
mod: note: imports must be built before being imported
mod: fatal error: returning to the gate for a mechanical issue
compilation terminated.
ninja: build stopped: subcommand failed.
此处评分最高的答案(来自 ComicSansMS)说我们可以使用实验功能来构建 C++20 模块: 如何使用 CMake 使用 c++20 模块?
CMake可以自动扫描模块依赖并构建项目吗?