C++ 宏定义

看到一段 C++ 代码,大致是说如果如果定义了 RUN_ALL_TESTS 就执行下面的代码,遂研究了一下。

#if defined(RUN_ALL_TESTS)
// some code here
#endif

首先 RUN_ALL_TESTS 是定义的宏:

#define RUN_ALL_TESTS // 空字符串
#define RUN_ALL_TESTS 1 // 赋值为 1

#if defined 为条件编译指令,它并不会考虑宏定义中有没有值。

#if defined(RUN_ALL_TESTS)
// some code here
#else
// some other code
#endif

除了在 .cpp 文件中定义,是否有其他方法对 RUN_ALL_TESTS 进行指定呢?可以在编译阶段进行指定:

  • CMakeLists.txt 文件中进行指定

    • add_definitions(-DRUN_ALL_TESTS) 或者 add_definitions(-DRUN_ALL_TESTS=1)

    • add_definitions已经逐渐被弃用,更推荐使用目标明确的 target_compile_definitions

      add_executable(my_target test.cpp)
      target_compile_definitions(my_target PRIVATE RUN_ALL_TESTS)
  • 在编译时 cmake -DRUN_ALL_TESTS=1 .
    (我测试时 cmake -DRUN_ALL_TESTS= . 不起作用,即必须赋值)

  • 在编译时 g++ -D RUN_ALL_TESTS myfile.cpp -o myfile

posted @   BuckyI  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示