【问题标题】:Using macros with bazel build使用带有 bazel 构建的宏
【发布时间】:2021-10-27 07:31:42
【问题描述】:

我正在使用宏来启用登录我的代码。另外,我正在使用 bazel 构建。 目前我需要更改我的 .cpp 文件以包含 #define 以启用此宏。有没有一种方法可以与bazel build 命令一起提供?

【问题讨论】:

    标签: c++ bazel bazel-rules


    【解决方案1】:

    一种选择是直接使用--cxxopt flag 控制#define

    以这段代码为例:

    #include <iostream>
    
    #ifndef _MY_MESSAGE_
        #define _MY_MESSAGE_ "hello"
    #endif
    
    
    int main(int argc, char const *argv[]) {
        std::cerr << "message: " _MY_MESSAGE_ "\n";
    
    #ifdef _MY_IDENTIFIER_
        std::cerr << "if branch \n";
    #else
        std::cerr << "else branch \n";
    #endif
        return 0;
    }
    

    不带标志的构建应导致以下结果:

    > bazel build :main
    ...
    > ./bazel-bin/main
    message: hello
    else branch
    

    通过设置标志:

    > bazel build --cxxopt=-D_MY_IDENTIFIER_ --cxxopt=-D_MY_MESSAGE_="\"hi\"" :main
    > ./bazel-bin/main
    message: hi
    if branch
    

    同样适用于bazel run:

    > bazel run --cxxopt=-D_MY_IDENTIFIER_ --cxxopt=-D_MY_MESSAGE_="\"hi\"" :main
    ...
    message: hi
    if branch
    

    (仅在 linux 上测试)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多