简体   繁体   中英

Using macros with bazel build

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 ?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM