Home > Back-end >  Using macros with bazel build
Using macros with bazel build

Time:10-27

I am using macro for enabling logging in my code. Also, I am using bazel build. Currently i need to change my .cpp file to include #define to enable this macro. Is there a way that i can provide this alongwith bazel build command ?

CodePudding user response:

One option would be to control the #define directly with the --cxxopt flag.

Consider for example this code:

#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;
}

Building without flags should result in the following:

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

While by settings the flags:

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

Same applies to bazel run:

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

(tested only on linux)

  • Related