Flags for mold with GCC only work for GCC 12.1 and later
CMake 3.29 is introducing direct support for linker selection through the LINKER_TYPE target property and CMAKE_LINKER_TYPE CMake variable.
The file at Modules/Platform/Linux-GNU.cmake unilaterally sets CMAKE_${lang}_USING_LINKER_MOLD to -fuse-ld=mold. But according to the README for mold:
For Clang: pass -fuse-ld=mold
For GCC 12.1.0 or later: pass
-fuse-ld=moldFor GCC before 12.1.0: the
-fuse-ldoption does not acceptmoldas a valid argument, so you need to use the-Boption instead. The-Boption tells GCC where to look for external commands likeld.If you have installed mold with
make install, there should be a directory named/usr/libexec/mold(or/usr/local/libexec/mold, depending on your$PREFIX), and theldcommand should be there. Theldis actually a symlink tomold. So, all you need is to pass-B/usr/libexec/mold(or-B/usr/local/libexec/mold) to GCC.If you haven't installed
ld.moldto any$PATH, you can still pass-fuse-ld=/absolute/path/to/moldto clang to use mold. However, GCC does not accept an absolute path as an argument for-fuse-ld.
I've included the parts for Clang in the above because Clang on Linux uses the same platform files as GCC, so it gets the same definitions for CMAKE_${lang}_USING_LINKER_MOLD.
It looks like we really need to be checking the GCC version and using the most appropriate flag for that version. The added complication of whether or not ld.mold is on the PATH probably should also be considered. We could just document that it must be on the PATH rather than resorting to passing an absolute path with -fuse-ld=.... That would simplify the logic and make things a bit more consistent between how we would treat GCC and Clang.
CC: @marc.chevrier