问题
有时我们需要根据Cmake编译时传入不同参数,运行我们不同分支的代码,用于支持不同场景,那么该如何解决?
解决思路
1、如何通过Cmake的编译命令传入参数?
cmake提供如下机制进行传递变量:
-D <var>:<type>=<value>, -D <var>=<value>
Create or update a CMake CACHE entry.
When CMake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a setting that takes priority over the project’s default value. The option may be repeated for as many CACHE entries as desired.
If the : portion is given it must be one of the types specified by the set() command documentation for its CACHE signature. If the : portion is omitted the entry will be created with no type if it does not exist with a type already. If a command in the project sets the type to PATH or FILEPATH then the will be converted to an absolute path.
This option may also be given as a single argument: -D:= or -D=.
2、如果为程序传递预处理宏?
cmake提供如下机制:add_compile_definitions
Add preprocessor definitions to the compilation of source files.
add_compile_definitions( …)
Adds preprocessor definitions to the compiler command line.
示例
CmakeLists.txt
if(${TEST} STREQUAL on)
add_compile_definitions(TEST)
endif()
add_executable(cmake_demo main.cpp)
main.cpp
#include <iostream>
int main()
{
#ifdef TEST
std::cout << "TEST marco is define\n";
#else
std::cout << "TEST marco is not define\n";
#endif
return 0;
}
效果:
编译:cmake …/ -DTEST=on && make
运行:./cmake_demo
输出:TEST marco is define
编译:cmake … && make
运行:./cmake_demo
输出:TEST marco is not define