c++ - 使用 CMAKE 检查编译器中是否启用了 c++11 功能

标签 c++ c++11 cmake

我正在使用 CMake 开发一个项目。我的代码包含 constexpr 方法,这些方法在 Visual Studio 2015 中允许,但在 Visual Studio 2013 中不允许。

如果指定的编译器支持该功能,我如何检查 CMakeLists.txt?我在 CMake 文档中看到过 CMAKE_CXX_KNOWN_FEATURES ,但我不明白如何使用它。

最佳答案

您可以使用 target_compile_features要求 C++11(/14/17) 特性:

target_compile_features(target PRIVATE|PUBLIC|INTERFACE feature1 [feature2 ...])

feature1CMAKE_CXX_KNOWN_FEATURES 中列出的功能.例如,如果你想在你的公共(public) API 中使用 constexpr,你可以使用:

add_library(foo ...)
target_compile_features(foo PUBLIC cxx_constexpr)

您还应该看看 WriteCompilerDetectionHeader module它允许将功能检测为选项,并在编译器不支持某些功能时为它们提供向后兼容性实现:

write_compiler_detection_header(
    FILE foo_compiler_detection.h
    PREFIX FOO
    COMPILERS GNU MSVC
    FEATURES cxx_constexpr cxx_nullptr
)

如果关键字 constexpr 可用,这里将生成一个包含 FOO_COMPILER_CXX_CONSTEXPR 的文件 foo_compiler_detection.h:

#include "foo_compiler_detection.h"

#if FOO_COMPILER_CXX_CONSTEXPR

// implementation with constexpr available
constexpr int bar = 0;

#else

// implementation with constexpr not available
const int bar = 0;

#endif

此外,如果当前编译器存在该功能,FOO_CONSTEXPR 将被定义并扩展为 constexpr。否则它将是空的。

FOO_NULLPTR 将被定义并扩展为 nullptr 如果当前编译器存在该功能。否则它将扩展为兼容性实现(例如 NULL)。

#include "foo_compiler_detection.h"

FOO_CONSTEXPR int bar = 0;

void baz(int* p = FOO_NULLPTR);

参见 CMake documentation .

关于c++ - 使用 CMAKE 检查编译器中是否启用了 c++11 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220265/

相关文章:

c++ - double 到 time 的转换

c++ - 如何将特征功能委托(delegate)给类(class)成员?

c++ - 在 C++11 中将映射函数添加到 vector

c++ - 除了静态库本身之外,停止 cmake target_link_libraries 链接静态库的两个目标文件

c++ - QT显示从网络访问管理器获取的图像

c++ - vfork()../nptl/sysdeps/unix/sysv/linux/raise.c : No such file or directory

c++ - 保留 std::initializer_list 的拷贝是否安全?这是什么道理?

ios - 自动创建 Xcode 项目 (.xcodeproj)

c++ - CMake 可以使用 c++ 而不是 mpicxx 来编译我的代码吗?

c++ - 为什么不将对象推送到此 vector (当它是结构的成员时)?