C++ CMake:如何传递预处理器宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9639449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:06:37  来源:igfitidea点击:

CMake: How to pass preprocessor macros

c++cmake

提问by Killrazor

How can I pass a macro to the preprocessor? For example, if I want to compile some part of my code because a user wants to compile unit test, I would do this:

如何将宏传递给预处理器?例如,如果我想编译我的代码的某些部分因为用户想要编译单元测试,我会这样做:

#ifdef _COMPILE_UNIT_TESTS_
    BLA BLA
#endif //_COMPILE_UNIT_TESTS_

Now I need to pass this value from CMake to the preprocessor. Setting a variable doesn't work, so how can I accomplish this?

现在我需要将此值从 CMake 传递给预处理器。设置变量不起作用,那么我该如何实现呢?

回答by Cat Plus Plus

add_definitions(-DCOMPILE_UNIT_TESTS)(cf. CMake's doc) ormodify one of the flag variables (CMAKE_CXX_FLAGS, or CMAKE_CXX_FLAGS_<configuration>) orset COMPILE_FLAGSvariable on the target.

add_definitions(-DCOMPILE_UNIT_TESTS)(cf. CMake's doc)修改标志变量之一 ( CMAKE_CXX_FLAGS, or CMAKE_CXX_FLAGS_<configuration>)COMPILE_FLAGS在目标上设置变量。

Also, identifiers that begin with an underscore followed by an uppercase letter are reserved for the implementation. Identifiers containing double underscore, too. So don't use them.

此外,以下划线开头后跟大写字母的标识符是为实现保留的。标识符也包含双下划线。所以不要使用它们。

回答by Lesque

If you have a lot of preprocessor variables to configure, you can use configure_file:

如果你有很多预处理器变量需要配置,你可以使用configure_file

Create a configure file, eg. config.h.inwith

创建一个配置文件,例如。config.h.in

#cmakedefine _COMPILE_UNIT_TESTS_
#cmakedefine OTHER_CONSTANT
...

then in your CMakeLists.txt:

然后在你的 CMakeLists.txt 中:

set(_COMPILE_UNIT_TESTS_ ON CACHE BOOL "Compile unit tests") # Configurable by user 
set(OTHER_CONSTANT OFF) # Not configurable by user
configure_file(config.h.in config.h)

in the build directory, config.his generated:

在构建目录中,config.h生成:

#define _COMPILE_UNIT_TESTS_
/* #undef OTHER_CONSTANT */

As suggested by robotik, you should add something like include_directories(${CMAKE_CURRENT_BINARY_DIR})to your CMakeLists.txtfor #include "config.h"to work in C++.

正如robotsik所建议的,您应该include_directories(${CMAKE_CURRENT_BINARY_DIR})CMakeLists.txtfor 中添加类似的内容以#include "config.h"在 C++ 中工作。