For a cc_binary target, how do I create a define that is inherited by its dependencies?

24 Views Asked by At

I have a bazel cc_binary target, lets call it common_library, that depends on other targets. I want this common_library to set a define that will activate code in its dependencies.

I need this since I am shipping an artifact with two libraries that support different communication. One should support sockets, and one support handles, and I want them both to be built by the same build.

I've tried all the following solutions, but none of them propegate the define to the dependencies.

...
    copts = select({
        ":test_config_settings": ["-DTEST_FLAG=1"],
        "//conditions:default": [],
    }),
    copts = ["-DTEST_FLAG"],
    local_defines = ["TESTFLAG=1"]
    defines = [
     "TEST_FLAG"
    ],
    local_defines = [
     "TEST_FLAG"
    ],
)


config_setting(
    name = "test_config_settings",
    define_values = {
        "TEST_FLAG": "1",
    },
)

I can't add --config=test_config_settings from the command line, since that would apply it on artifacts even though I don't want to one of the builds of this library.

To test this, I set up a test project with the following structure:

├── lib1
│   ├── BUILD
│   ├── lib1.cpp
│   └── lib1.h
├── main
│   ├── .bazelrc
│   ├── BUILD
│   └── main.cpp
└── WORKSPACE

and with the following code:

// main/main.cpp
#include "lib1/lib1.h"

int main() {
    print_hello_lib1();
    return 0;
}
# main/BUILD
cc_binary(
    name = "main",
    srcs = ["main.cpp"],
    deps = [
        "//lib1:lib1",
    ],
    copts = select({
        ":test_config_settings": ["-DTEST_FLAG=1"],
        "//conditions:default": [],
    }),
    local_defines = ["TESTFLAG=1"]
    copts = ["-DTEST_FLAG"],
    defines = [
     "TEST_FLAG=1"
    ],
)


config_setting(
    name = "test_config_settings",
    define_values = {
        "TEST_FLAG": "1",
    },
)
// lib1/lib1.cpp
#include <iostream>

void print_hello_lib1() {
    #ifdef TEST_FLAG
    std::cout << "Hello from lib1!\n";
    #endif
}
# lib1/BUILD
cc_library(
    name = "lib1",
    srcs = ["lib1.cpp"],
    hdrs = ["lib1.h"],
    visibility = ["//visibility:public"],
    copts = select({
        "//main:test_config_settings": ["-DTEST_FLAG=1"],
        "//conditions:default": [],
    }),
)
# main/.bazelrc
build:test_config_settings --copt=-DTEST_FLAG=1
build --config=test_config_settings

Is it possible to do this in bazel?

0

There are 0 best solutions below