Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use mold linker with bazel and gcc10?

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.

like image 778
very hit Avatar asked Sep 12 '25 15:09

very hit


2 Answers

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.)

like image 173
Benjamin Peterson Avatar answered Sep 14 '25 05:09

Benjamin Peterson


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.gold.backup
ln -s /usr/local/bin/mold /usr/bin/ld.gold
like image 45
very hit Avatar answered Sep 14 '25 07:09

very hit