我正在与CMake开发一个项目。我的代码包含constexpr
方法,这些方法在Visual Studio 2015中是允许的,但在Visual Studio 2013中不允许。
如果指定的编译器支持该功能,我如何检查CMakeLists.txt
?我在CMake文档CMAKE_CXX_KNOWN_FEATURES
中看到过,但我不明白如何使用它。
答案 0 :(得分:7)
您可以使用target_compile_features来要求C ++ 11(/ 14/17)功能:
target_compile_features(target PRIVATE|PUBLIC|INTERFACE feature1 [feature2 ...])
将feature1
作为CMAKE_CXX_KNOWN_FEATURES
中列出的功能。例如,如果要在公共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
)
如果关键字foo_compiler_detection.h
可用,则会生成一个文件FOO_COMPILER_CXX_CONSTEXPR
并定义constexpr
:
#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);