bazel-contrib / bazel-contrib/rules_foreign_cc
Cmake uses C++ compilation flags for linking
- Dominant language
- Starlark
- Stars
- 737
- Forks
- 270
- PR merge metrics
- No merged PRs in 30d
Description
There's an issue that affects some CMake projects, nameli X265 and AOM, that is that they use the C++ compiler for linking, which means they also pick up all CXX_FLAGS from the crosstool file. When the CC toolchain configures `CXX_FLAGS` to include `-x c++`, this gets passed to the toolchain config as `CMAKE_CXX_FLAGS_INIT`, which ends up being used in the link step too, as described in [the relevant CMake documentation](https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_FLAGS.html#variable:CMAKE_%3CLANG%3E_FLAGS).
The issue here seems to be that in Bazel, `CXX_FLAGS` are meant for compilation only, and not for linking, and thus passing them on to the toolchain file as `CMAKE_CXX_FLAGS_INIT` isn't the right thing to do probably.
I could work around this issue by modifying `@rules_foreign_cc` to instead pass the compile flags using `add_compile_options`, but I was doing that manually for this single flag, and I had to also remove it from the `CMAKE_CXX_FLAGS_INIT`:
```cmake
add_compile_options($<$:-xc++>)
```
There should be a better way to specify compile flags and link flags, by translating the Bazel toolchain info to the appropriate options in the toolchain file, rather than setting these INIT flags that end up being used for both compilation and linking. In general, the toolchain file should be constructed somehow… in a better way, but I'm not sure how or what is the right mapping from Bazel toolchain info values to CMake options.
For the case of `-xc++` this simple workaround is sufficient, but it would be better to come up with a more complete solution. I'd be happy to contribute this if someone could help figure out what's the right mapping from Bazel features to CMake options.
---
There's some more detail in https://github.com/tweag/rules_nixpkgs/discussions/467.
Contributor guide
Research direction
Start with the linked CMake documentation on CMAKE__FLAGS and the additional detail in rules_nixpkgs discussion 467. Trace how Bazel toolchain CXX_FLAGS become CMAKE_CXX_FLAGS_INIT in the generated CMake toolchain file, then define a mapping that keeps compile-only flags out of linking while preserving the reported -xc++ workaround and covering the broader flag cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cmake
- Domain
- build-system
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100