我正在使用 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 ...])
feature1
是 CMAKE_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/