Search code examples
c++bazel

Bazel: pass a build time variable to C++ program


I've this C++ program that prints the value of VERSION string:

#include <iostream>

int main() {
    std::cout << "Version: " << VERSION << std::endl;
    return 0;
}

I want to change the value of VERSION (a string) at build time. This is my Bazel config that contains a default value for VERSION as local_defines:

cc_binary(
    name = "main",
    srcs = ["main.cpp"],   
    local_defines = ["VERSION=\\\"alpha\\\""],
)

When I call it like this, it still prints alpha and NOT the new value I'm passing for VERSION.

bazel run --define VERSION=beta main
INFO: Analyzed target //:main (1 packages loaded, 2 targets configured).
INFO: Found 1 target...
Target //:main up-to-date:
  bazel-bin/main
INFO: Elapsed time: 0.965s, Critical Path: 0.80s
INFO: 4 processes: 2 internal, 2 darwin-sandbox.
INFO: Build completed successfully, 4 total actions
INFO: Build completed successfully, 4 total actions
Version: alpha

Why is this not working?


Solution

  • cc_binary.local_defines and the --define flag are separate things, even though they share the same name. local_defines supports "Make" variable substitution, which means this will work: local_defines = ["VERSION=\\\"$(VERSION)\\\""].