检查是否使用CMAKE在编译器中启用了c ++ 11功能 [英] check if a c++11 feature is enabled in compiler with CMAKE
问题描述
我正在与CMake合作开发一个项目。我的代码包含 constexpr
方法,在Visual Studio 2015中允许使用,但在Visual Studio 2013中不允许。
I'm developing a project with CMake. My code contains constexpr
methods, that are allowed in Visual Studio 2015, but not in Visual Studio 2013.
如何是否可以检查 CMakeLists.txt
是否受指定编译器支持?我已经在CMake文档中看到 CMAKE_CXX_KNOWN_FEATURES
,但我不知道如何使用它。
How can I check in the CMakeLists.txt
if the feature is supported by the specified compiler? I've seen in CMake documentation CMAKE_CXX_KNOWN_FEATURES
, but I didn't understand how to use it.
推荐答案
您可以使用 target_compile_features 要求具有C ++ 11(/ 14/17)功能:
You can use target_compile_features to require a C++11(/14/17) feature:
target_compile_features(target PRIVATE|PUBLIC|INTERFACE feature1 [feature2 ...])
具有 feature1
是 CMAKE_CXX_KNOWN_FEATURES
。例如,如果要在公共API中使用 constexpr
,则可以使用:
With feature1
being a feature listed in CMAKE_CXX_KNOWN_FEATURES
. For example, if you want to use constexpr
in your public API, you can use:
add_library(foo ...)
target_compile_features(foo PUBLIC cxx_constexpr)
您还应该查看 WriteCompilerDetectionHeader
模块,该模块允许将功能检测为选项,并在编译器不支持某些功能的情况下向后兼容实现:
You should also take a look at the WriteCompilerDetectionHeader
module which allows to detect features as options, and provides a backward compatibility implementation for some features if the compiler does not support them:
write_compiler_detection_header(
FILE foo_compiler_detection.h
PREFIX FOO
COMPILERS GNU MSVC
FEATURES cxx_constexpr cxx_nullptr
)
此处是文件 foo_compiler_detection.h $ c如果关键字
constexpr
可用,将使用定义的 FOO_COMPILER_CXX_CONSTEXPR
生成$ c>:
Here a file foo_compiler_detection.h
will be generated with FOO_COMPILER_CXX_CONSTEXPR
defined if the keyword constexpr
is available:
#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 如果当前编译器存在该功能,将定义code>并将其扩展为
constexpr
。否则将为空。
Moreover, FOO_CONSTEXPR
will be defined and will expand to constexpr
if the feature exists for the current compiler. It will be empty otherwise.
FOO_NULLPTR
将被定义并扩展为 nullptr
(如果当前编译器存在该功能)。否则它将扩展到兼容性实现(例如 NULL
)。
FOO_NULLPTR
will be defined and will expand to nullptr
if the feature exists for the current compiler. It will expand to a compatibility implementation otherwise (e.g. NULL
).
#include "foo_compiler_detection.h"
FOO_CONSTEXPR int bar = 0;
void baz(int* p = FOO_NULLPTR);
请参见 CMake文档。
这篇关于检查是否使用CMAKE在编译器中启用了c ++ 11功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!