CMake传递相关宏至源代码

问题

有时我们需要根据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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值