我刚刚开始学习 C++ 编程,我使用的书籍重点关注新的模块系统以取代 #include 方法。
对于 make,我发现 Makefiles 允许首先将 #includes(例如 iostream)转换为模块文件(g++ 为它们提供 .gcm 扩展名),然后使用它们来编译二进制文件。
现在,由于我正在使用 CLion 并且它使用了 CMake,因此能够使用 CMake 来完成此操作会很棒,但我只能通过创建一个 #includes 标头并导出的个人模块文件来找到有关如何执行此操作的信息。通过使用函数来请求功能。
有谁知道这是否(已经)可能,还是我们必须等待 GCC 或 CLANG 包含标准库模块(例如 C++20 的 print 或 C++23 的 std)?
我找到的大部分信息都是这样解决的:
主.cpp
import foo;
int main() {
print("Hello, World!\n");
}
foo.cppm
module;
#include <iostream>
#include <string>
export module foo;
export void print(std::string s) { std::cout << s; }
CMakeLists.txt
cmake_minimum_required(VERSION 3.28)
project(cmake_module_example CXX)
set(CMAKE_CXX_STANDARD 23)
# Create a library
add_library(my_modules)
# Add the module file to the library
target_sources(my_modules
PUBLIC
FILE_SET CXX_MODULES FILES
foo.cppm
)
# Create an executable
add_executable(hello main.cpp
main.cpp)
# Link to the library foo
target_link_libraries(hello my_modules)
我正在使用 Debian 12 并尝试使用 gcc-14 和 clang-17 CLion 使用的构建工具是 ninja,除非它们附带更新版本,否则当前版本是 1.11.1
它终于出现在 CMake 3.30 中的实验标志后面:https://www.kitware.com/import-std-in-cmake-3-30/
# CMake 3.30 is required for C++23 `import std` support; we use 3.29.20240416
# here so that in-development versions satisfy it.
cmake_minimum_required(VERSION 3.29.20240416 FATAL_ERROR)
# Set experimental flag to enable `import std` support from CMake.
# This must be enabled before C++ language support.
set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD
# This specific value changes as experimental support evolves. See
# `Help/dev/experimental.rst` in the CMake source corresponding to
# your CMake build for the exact value to use.
"0e5b6991-d74f-4b3d-a41c-cf096e0b2508")
# C++ needs to be enabled.
project(import_std LANGUAGES CXX)
# Tell CMake that we explicitly want `import std`. This will initialize the
# property on all targets declared after this to 1
set(CMAKE_CXX_MODULE_STD 1)
# Make a library.
add_library(uses_std STATIC)
# Add sources.
target_sources(uses_std
PRIVATE
uses_std.cxx)
# Tell CMake we're using C++23 but only C++20 is needed to consume it.
target_compile_features(uses_std
PRIVATE cxx_std_23
INTERFACE cxx_std_20)
# Make an executable.
add_executable(main)
# Note that this source is *not* allowed to `import std` as it ends up
# with only C++20 support due to the `uses_std` INTERFACE requirements.
target_sources(main
PRIVATE
main.cxx)
target_link_libraries(main PRIVATE uses_std)