Search code examples
bazel

Sending specific compilation flags for static compilation with Bazel Build


In my project we have code that when compiled for static linkage there must be a define added when compiling the code. Let's assume it's -DSTATIC_COMPILATION.

My question: Is it possible to control compilation flags when requesting a static linkage or any compilation flags based on linkage binding?

Thinks I know I can do:

  1. Add a --copt '-DSTATIC_COMPILATION' to the command line bazel build
  2. Configure a bazelrc file that can provide such configuration by passing bazel build --config=static_comp - which is nice, but I'm not sure it will pass to other packages when taking this package as external package - I could be wrong here...

What are the options I'm missing?


Solution

  • The short answer is that there is no way in Bazel today to get it to set a flag based on whether the code will be statically or dynamically linked.

    Bazel's cc_library does compile code twice on architectures that require PIC for dynamic linking, but do not require PIC for static linking - once with and once without PIC. This is mostly done for performance of the statically linked executables, as non-PIC code is generally faster.

    Note that cc_test rules in Bazel are dynamically linked by default while cc_binary rules are statically linked by default, so the PIC/no-PIC distinction requires double compilation of almost all C/C++ source code. For additional complexity, note that PIE executables require PIC-compiled code, so if you want ASLR, which requires PIE executables, then the code is always compiled as PIC.

    However, the support for PIC/no-PIC is hard-coded in cc_library, and I don't see any obvious way to 'abuse' it to do what you want. You could conceivably hack up a crosstool to declare that the arch requires PIC for dynamic linking, but not static linking, and then declare with PIC in both cases anyway and also set the additional flag. This would result in .pic.o and .o output files, although both would contain PIC code. This isn't workable if you can't control the crosstool, and I wouldn't recommend doing this.

    That said, there may be other ways to achieve what you want. Mind elaborating why you need to have a special case for statically linked code?