how to use mold linker with bazel and gcc10?

1.5k Views Asked by At

mold is the latest modern linker with high speed, I want to use it to replace default ld linker when compiling our heavy c++ repository.

I use Bazel + GCC 10.2 to compile, and mold docs provide a gcc -B/mold/path solution. However I don't find a way to pass this CLI option to bazel.

I tried bazel build --linkopt=-B/usr/local/libexec/mold //src:XXX or --copt=-B/usr/local/libexec/mold, but both don't work, bazel still use old linker.

I can ensure mold has been installed on my system, because I can compile c++ helloworld program link by mold directly run g++ -B/usr/local/libexec/mold.

2

There are 2 best solutions below

0
very hit On BEST ANSWER

Peterson's answer can work in most cases, but if you are using an outdated Bazel version such as 0.2x like me, there is a bug for Bazel link stage. The bug leads to user link flags always be overwrite by Bazel default link flags.

To verify the bug, run bazel build --subcommands --linkopt=-B/any_path <your-target>, and you will see details about link stage flags.

In my case, Bazel default flag -fuse-ld=gold and -B/usr/bin always occurs after user flags, so I have to create a soft link /usr/bin/ld.gold -> /usr/local/bin/mold. This workaround works for me.

So try:

mv /usr/bin/ld.gold /usr/bin/ld.glod.backup
ln -s /usr/local/bin/mold /usr/bin/ld.gold
2
Benjamin Peterson On

Try --linkopt=-fuse-ld=bfd --linkopt=-B/usr/local/libexec/mold --sandbox_block_path=/usr/bin/ld.bfd.

(Bazel knows about some linkers such as GNU gold and lld. If it detects, them it will explicitly tell the compilation driver to use them, which bypasses the mold ld in /usr/local/libexec/mold.)