how to set meson link dependency for buildin lib as "-lm -lrt" - meson-build

on meson build, dependencies are resolved by pkg-config/cmake ...
but for system libs, no docs. I only find 2 of them:
zlib stands for -lz
threads stands for -lpthread
then how can I link -lm -lrt ?
"m"
"math"
"libm"
runtime
all guess fail.

ok, method found in doc:
cc = meson.get_compiler('c')
m_dep = cc.find_library('m', required : false)
executable("abc", dependencies : m_dep)
for common libs that's not good design.
why not make it easy? such as:
m_dep = dependency('m', method : 'build-in')

Related

Use non-default linker (lld, mold, gold) with CMake [duplicate]

I want to setup a custom toolchain with CMake. I've set the compiler but I don't know how to set the linker. This error is reported because CMake try to use the compiler to link:
The C compiler "xgcc.exe" is not able to compile a simple test program.
Here there is a snippet of my toolchain file
# specify the cross compiler
INCLUDE(CMakeForceCompiler)
SET(CMAKE_C_COMPILER xgcc.exe)
SET(CMAKE_CXX_COMPILER xgcc.exe)
#CMAKE_FORCE_C_COMPILER(xgcc.exe GNU)
#CMAKE_FORCE_CXX_COMPILER(xgcc.exe GNU)
I've tried to force the compiler but the linker problem will not be solved.
The link command line is set in Modules/CMake{C,CXX,Fortran}Information.cmake and defaults to using the compiler, not CMAKE_LINKER (see source code). This can be changed by replacing the rule that builds the link command line, which lives in variables CMAKE_CXX_LINK_EXECUTABLE (and friends). NB that variable does not indicate the path to the linker executable; it says how to link an executable!
One approach is to set that rule to use the linker, e.g.
cmake -DCMAKE_LINKER=/path/to/linker -DCMAKE_CXX_LINK_EXECUTABLE="<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
See also this post from CMake mailing list and this one - this also makes a natural place to prepend a linker modifier to another linker.
As Mabraham points out, CMake calls the compiler to do the linking. So, by far the simplest solution to this is to LET IT, and instead tell the compiler to run a different linker when called.
Which, as noted in this other answer — but now it's even a documented option in gcc --help=common — is as easy as:
cmake -DCMAKE_CXX_FLAGS="-fuse-ld=lld"
g++ or clang++ will get passed the -fuse-ld=lld1 flag on every call, and when they do any linking they'll use the specified command instead of the built-in default. Easy-peasy, and CMake need not concern itself with such things at all.
(BTW, the option is parsed (-f) (use-ld) (=) (lld), there's no "fuse" option to gcc.)
Notes
When using Clang, lld can be replaced with whatever other linker command you want to use, like ld.exe, ld.gold, mingw32/bin/ld.exe, etc.
GCC isn't as flexible, its -fuse-ld only accepts one of three possible arguments: lld, bfd, or gold. It will invoke the first matching ld.foo executable it finds on the PATH. (Thanks to bviktor for pointing out GCC's limitations for alternate linker selection.)
CMake only gives you direct control over the compiler for each language. To call the linker, it goes through the configured compiler. This means that there is no universal way to set the linker in CMake, you must configure your compiler to use the linker you intend.
Such flags need to be set before CMake's compiler detection routines run because it will try to compile a test binary. The best way to do this is by creating a toolchain file. The best way to set these flags in the toolchain file is like so:
# e.g. to use lld with Clang
set(CMAKE_EXE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_MODULE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_SHARED_LINKER_FLAGS_INIT "-fuse-ld=lld")
These three variables control the (default) set of linker flags for executables, loadable modules, and shared libraries, respectively. There is no need to handle CMAKE_STATIC_LINKER_FLAGS_INIT (for static libraries) here because the archiver is invoked, rather than the linker.
You can then set the toolchain file when you first run CMake by setting -DCMAKE_TOOLCHAIN_FILE=/path/to/toolchain.cmake at the command line. As of CMake 3.21, you will be able to pass --toolchain /path/to/toolchain.cmake instead (which is entirely equivalent, but a little less typing).
Set the variable ${CMAKE_LINKER} either in CMakeCache.txt or after ccmake . under advanced options.
I have to use CMAKE_CXX_LINK_EXECUTABLE, CMAKE_C_LINK_EXECUTABLE variable:
SET(CMAKE_C_LINK_EXECUTABLE "c:\\MoSync\\bin\\pipe-tool.exe")
I had success with doing
add_link_options("-fuse-ld=lld")
It is a variation on the previous answers here. The difference is the CMake command I use to set the flag.
Adding it to CMAKE_CXX_FLAGS has the disadvantage of then also having to add -Wno-unused-command-line-argument as the flags get also added to compilation commands, not only to linking ones.
The disadvantage of CMAKE_SHARED_LINKER_FLAGS is that you have to add it multiple times, to _SHARED_, _EXE_, and maybe I forgot something.
Here is a CMake function which sets linker based on some predefined arbitrary rules (Clang -> lld-version or lld, GCC -> gold).
The important parts:
Search for lld-version which matches the Clang compiler version (ex. lld-13 if Clang 13.x.x is used), falls back to lld if not found
add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR}")
Use all system threads when linker is set to gold:
add_link_options("-fuse-ld=gold;LINKER:--threads,--thread-count=${HOST_PROC_COUNT}")
The example is a bit too long because of comments, logs and custom logic, but it is self-contained and could be useful staring point for beginners.
function(select_best_linker) #lld for Clang and GNU gold for GCC
if (UNIX AND NOT APPLE)
include(ProcessorCount)
ProcessorCount(HOST_PROC_COUNT)
if(${CMAKE_CXX_COMPILER_ID} MATCHES Clang)
# By default LLD uses all system threads.
# This could be tweaked for versions 11+ (--threads=1), but cannot be disabled for older versions
# add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR};LINKER:--threads=${HOST_PROC_COUNT}") #LLD>=11
# add_link_options("-fuse-ld=lld;LINKER:--threads")#LLD <= 10 this is the default state
string(REPLACE "." ";" VERSION_LIST ${CMAKE_CXX_COMPILER_VERSION})
list(GET VERSION_LIST 0 CLANG_VERSION_MAJOR) #extract major compiler version
find_program(LLD_PROGRAM_MATCH_VER lld-${CLANG_VERSION_MAJOR}) #search for lld-13 when clang 13.x.x is used
find_program(LLD_PROGRAM lld) #else find default lld
if (LLD_PROGRAM_MATCH_VER) #lld matching compiler version
message(STATUS "Set linker to LLD (multi-threaded): ${LLD_PROGRAM_MATCH_VER}")
add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR}")
elseif(LLD_PROGRAM) #default lld
message(STATUS "Set linker to LLD (multi-threaded): ${LLD_PROGRAM}")
add_link_options("-fuse-ld=lld")
endif(LLD_PROGRAM_MATCH_VER)
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES GNU)
find_program(GNU_GOLD_PROGRAM gold)
if (GNU_GOLD_PROGRAM)
message(STATUS "Set linker to GNU gold: ${GNU_GOLD_PROGRAM}, using threads: ${HOST_PROC_COUNT}")
add_link_options("-fuse-ld=gold;LINKER:--threads,--thread-count=${HOST_PROC_COUNT}")
endif(GNU_GOLD_PROGRAM)
endif(${CMAKE_CXX_COMPILER_ID} MATCHES Clang)
endif(UNIX AND NOT APPLE)
endfunction(select_best_linker)
Tested on:
Ubuntu 20.04
CMake 3.16.3
GCC 9.4.0
Clang-12
Clang-13
GNU gold (GNU Binutils 2.37) 1.16
LLD 10.0.0 (compatible with GNU linkers)
Ubuntu LLD 13.0.1 (compatible with GNU linkers)
For completeness, another full-proof option is to just link /usr/bin/ld to ld.gold by running
sudo ln -sf /usr/bin/x86_64-linux-gnu-ld.gold /usr/bin/ld
as suggested here
There is another way to do it, gcc has a "-fuse-ld" option, you can set LINKER_FLAGS in CMakeLists.txt like these:
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fuse-ld=lld")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld")
then the custom specified linker should be invoked.

Building SDL2_image as a CMake external project

I've been trying to create a CMake-based build-system for a project that is supposed to use SDL2_image library. I do not want to force user to install any libraries to the system to be able to build the project, so I took advantage of the CMake's ability to download and build dependencies (freetype, SDL2 and SDL2_image) from source code as External Projects.
Everything is fine with freetype and SDL2 (which both include CMakeLists.txt files out of the box), but I've ran out of ideas how to make it work for SDL2_image. CMake's external projects support custom configuration and building settings which I used in different variants with no success.
The CMake file itself can be found here, but the problematic part is this:
# SDL_image library
ExternalProject_Add(sdl2_image_project
URL https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.0.tar.gz
DEPENDS sdl2_project
PREFIX ${LIBS_DIR}/SDL2_image
CONFIGURE_COMMAND LDFLAGS=-L${SDL2_BIN} CFLAGS=-I${SDL2_SRC}/include SDL2_CONFIG=${SDL2_BIN}/sdl2-config <SOURCE_DIR>/configure --prefix=<INSTALL_DIR> --enable-shared=no
BUILD_COMMAND make
INSTALL_COMMAND ""
)
An error occurs while building sdl2_image_project. Some trivial research discovered that the error is generated by the undefined references to parts of libdl. Here is a tiny part of the hole error:
libtool: link: gcc -I/home/snikitin/_src/img_glypher/libs/SDL2/src/sdl2_project/include -I/usr/local/include/SDL2 -D_REENTRANT -o showimage showimage.o -Wl,-rpath -Wl,/usr/local/lib -pthread -L/home/snikitin/_src/img_glypher/libs/SDL2/src/sdl2_project-build ./.libs/libSDL2_image.a -L/usr/local/lib -lSDL2 -pthread
/home/snikitin/_src/img_glypher/libs/SDL2/src/sdl2_project-build/libSDL2.a(SDL_dynapi.c.o): In function `get_sdlapi_entry':
/home/snikitin/_src/img_glypher/libs/SDL2/src/sdl2_project/src/dynapi/SDL_dynapi.c:227: undefined reference to `dlopen'
I think the problem takes place due to the fact that linker tries to create a shared version of SDL2_image library while linking it to a static libSDL2.a. The thing is - if this is right - SDL2 building step creates both static and shared versions of itself so one would assume that linker would use libSDL2-2.0.so instead (I do not actually need a shared library - just the static one, but I do not know how to prevent the build system from trying to create it apart from passing --enable-shared=no to SDL2_image configure script, which does not help in this case).
After a lot of googling I've discovered that the possible source of the problem is that sdl2-config (which is called to get some flags for compiler during SDL_image building) may be called with wrong arguments and produces wrong cflags which confuse everything else. But I'm not sure that is the case and also I do not know how to influence sdl2_config call from CMake (configure --help does not seem to unveil any useful options for this situation).
I am running Ubuntu 14.04 x64 if it matters in any way. Would appreciate any advice!
Looks like you need to link some libraries like m and dl. It can be fixed by providing
custom sdl2-config file. Copy sdl2-config from extracted archive and substitute --libs result:
--libs)
echo -L${exec_prefix}/lib -Wl,-rpath,${libdir} -pthread -lSDL2 -lm -ldl
;;
Note that order is important (that's why just modifying LIBS not works for me).
Now this file can be used in your ExternalProject_Add command instead of SDL2_CONFIG=${SDL2_BIN}/sdl2-config:
...
... CFLAGS=-I${SDL2_SRC}/include SDL2_CONFIG=${CMAKE_CURRENT_LIST_DIR}/sdl2-config <SOURCE_DIR>/configure
...

Automake doesn't recognize Objective-C/C++

I have configure.ac which is designed for building a shared library (both linux and macos). Now I'd like to add special demo app which uses this library and shows its features. However this demo app is only for MacOS and has .mm file in it (main.mm). I'm trying to define a target for this demo app in this way:
if OS_DARWIN
EXTRA_PROGRAMS = app-demo
app_demo_CC = OBJC
app_demo_CXX = OBJC
app_demo_SOURCES = demoapp/config.cc demoapp/config.h \
demoapp/main.mm demoapp/AppDelegate.m \
demoapp/renderer-stub.cc demoapp/renderer-stub.h \
demoapp/view.cc demoapp/view.h
app_demo_CPPFLAGS = ... # include directories here
app_demo_LDFLAGS = ... # libraries and library search paths
endif
That's my top-level Makefile.am and as you can see, demoapp folder has all the sources for the demo app and two Objective-C files: main.mm and AppDelegate.m.
However, when I try to run make app-demo, I'm getting this:
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
Which means (and I confirm it from the make logs) that main.mm hasn't been compiled, neither linked.
Does anyone knows workarounds for this?
I don't think this is enough information to debug the problem.
I think automake supports ObjC++. Do you get errors when invoking automake? Does your configure.ac invoke AC_PROG_OBJCXX? If you try compiling the files by hand, does it work?
Resolved by defining separate target in Makefile.am like this:
.mm.o :
$(OBJCXX) -x objective-c++ -c #DEFS# $(CPPFLAGS) $(app_demo_CPPFLAGS) $< -o $#

How to set warning level in CMake?

How to set the warning level for a project (not the whole solution) using CMake? Should work on Visual Studio and GCC.
I found various options but most seem either not to work or are not consistent with the documentation.
In modern CMake, the following works well:
if(MSVC)
target_compile_options(${TARGET_NAME} PRIVATE /W4 /WX)
else()
target_compile_options(${TARGET_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif()
My colleague suggested an alternative version:
target_compile_options(${TARGET_NAME} PRIVATE
$<$<CXX_COMPILER_ID:MSVC>:/W4 /WX>
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-Wall -Wextra -Wpedantic -Werror>
)
Replace ${TARGET_NAME} with the actual target name. -Werror is optional, it turns all warnings into errors.
Or use add_compile_options(...) if you want to apply it to all targets as suggested by #aldo in the comments.
Also, be sure to understand the difference between PRIVATE and PUBLIC (public options will be inherited by targets that depend on the given target).
As #davidfong notes in the comments, since CMake v3.24, there is the CMAKE_COMPILE_WARNING_AS_ERROR variable that switches on treating compile warings as errors. In case it is set inside CMakeLists.txt, the user can still turn it off with the --compile-no-warning-as-error cmake flag. In case you want to add warning-as-error manually, add /WX in Windows and -Werror elsewhere to target_compile_options.
UPDATE: This answer predates the Modern CMake era. Every sane CMake user should refrain from fiddling with CMAKE_CXX_FLAGS directly and call the target_compile_options command instead. Check the mrts' answer which presents the recommended best practice.
You can do something similar to this:
if(MSVC)
# Force to always compile with W4
if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
endif()
elseif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
# Update if necessary
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic")
endif()
Some CMake modules I've written include experimental cross-platfrom warning suppression:
sugar_generate_warning_flags(
target_compile_options
target_properties
ENABLE conversion
TREAT_AS_ERRORS ALL
)
set_target_properties(
foo
PROPERTIES
${target_properties}
COMPILE_OPTIONS
"${target_compile_options}"
)
Result for Xcode:
Set CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION Xcode attribute
(aka build settings -> warnings -> suspicious implicit conversions -> YES)
Add compiler flag: -Werror
Makefile gcc and clang:
Add compiler flags: -Wconversion, -Werror
Visual studio:
Add compiler flags: /WX, /w14244
Links
List of available warnings
Usage and more options
As per Cmake 3.24.2 documentation:
if (MSVC)
# warning level 4 and all warnings as errors
add_compile_options(/W4 /WX)
else()
# lots of warnings and all warnings as errors
add_compile_options(-Wall -Wextra -pedantic -Werror)
endif()
GCC and Clang share these flags, so this should cover all 3.
Here is the best solution I found so far (including a compiler check):
if(CMAKE_BUILD_TOOL MATCHES "(msdev|devenv|nmake)")
add_definitions(/W2)
endif()
The GCC equivalent is -Wall (untested).
if(MSVC)
string(REGEX REPLACE "/W[1-3]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
endif()
If you use target_compile_options - cmake will try to use double /W* flag, which will give warning by compiler.
How to set the warning level for a project (not the whole solution) using CMake?
(I assume this to mean a CMake target, and not a CMake project.)
I found various options but most seem either not to work or are not consistent with the documentation.
Kitware's APIs may be trying to deter you from making your build system brittle and error-prone. The special-casing encouraged by other answers to this question violate at least two important principles of modern CMake build systems...
Firstly, prefer not to specify toolchain-specific details in CMakeLists.txt files. It makes the build system brittle. For example, if a new warning appears in a future version of the toolchain, the compiler will emit an error and your user may need to hack your project in order to build the target.
Instead, write toolchain-agnostic CMakeLists.txt files and preserve the user's ability to customise as they see fit. Ideally, your project should build everywhere with vanilla toolchain configuration - even if that doesn't enable your preferred warnings by default.
Secondly, if you intend to link binaries together, flags should be consistent. This reduces the risk of incompatibility which could result in an ill-formed program. However, warning flags are unlikely to affect code generation, so it may be safe to vary these between the targets you link together.
So... if you wish to specify flags per toolchain and if you absolutely must have different flags for different targets, use custom variables:
# CMakeLists.txt
project(my_project)
add_executable(my_target source_file.cpp)
target_compile_options(my_target PRIVATE "${MY_PROJECT_ELEVATED_WARNING_FLAGS}")
There are many ways to set these variables, such as CMakeCache.txt, a toolchain file, and via CMAKE_PROJECT_INCLUDE_BEFORE. But the simplest way is on the command line during configuration, for GCC
cmake -DMY_PROJECT_ELEVATED_WARNING_FLAGS:STRING="-Wall;-Wextra;-Wpedantic;-Werror" <path-to-project>
for MSVC
cmake -DMY_PROJECT_ELEVATED_WARNING_FLAGS:STRING="/W4;/WX" <path-to-project>

CMake: use a custom linker

I want to setup a custom toolchain with CMake. I've set the compiler but I don't know how to set the linker. This error is reported because CMake try to use the compiler to link:
The C compiler "xgcc.exe" is not able to compile a simple test program.
Here there is a snippet of my toolchain file
# specify the cross compiler
INCLUDE(CMakeForceCompiler)
SET(CMAKE_C_COMPILER xgcc.exe)
SET(CMAKE_CXX_COMPILER xgcc.exe)
#CMAKE_FORCE_C_COMPILER(xgcc.exe GNU)
#CMAKE_FORCE_CXX_COMPILER(xgcc.exe GNU)
I've tried to force the compiler but the linker problem will not be solved.
The link command line is set in Modules/CMake{C,CXX,Fortran}Information.cmake and defaults to using the compiler, not CMAKE_LINKER (see source code). This can be changed by replacing the rule that builds the link command line, which lives in variables CMAKE_CXX_LINK_EXECUTABLE (and friends). NB that variable does not indicate the path to the linker executable; it says how to link an executable!
One approach is to set that rule to use the linker, e.g.
cmake -DCMAKE_LINKER=/path/to/linker -DCMAKE_CXX_LINK_EXECUTABLE="<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
See also this post from CMake mailing list and this one - this also makes a natural place to prepend a linker modifier to another linker.
As Mabraham points out, CMake calls the compiler to do the linking. So, by far the simplest solution to this is to LET IT, and instead tell the compiler to run a different linker when called.
Which, as noted in this other answer — but now it's even a documented option in gcc --help=common — is as easy as:
cmake -DCMAKE_CXX_FLAGS="-fuse-ld=lld"
g++ or clang++ will get passed the -fuse-ld=lld1 flag on every call, and when they do any linking they'll use the specified command instead of the built-in default. Easy-peasy, and CMake need not concern itself with such things at all.
(BTW, the option is parsed (-f) (use-ld) (=) (lld), there's no "fuse" option to gcc.)
Notes
When using Clang, lld can be replaced with whatever other linker command you want to use, like ld.exe, ld.gold, mingw32/bin/ld.exe, etc.
GCC isn't as flexible, its -fuse-ld only accepts one of three possible arguments: lld, bfd, or gold. It will invoke the first matching ld.foo executable it finds on the PATH. (Thanks to bviktor for pointing out GCC's limitations for alternate linker selection.)
CMake only gives you direct control over the compiler for each language. To call the linker, it goes through the configured compiler. This means that there is no universal way to set the linker in CMake, you must configure your compiler to use the linker you intend.
Such flags need to be set before CMake's compiler detection routines run because it will try to compile a test binary. The best way to do this is by creating a toolchain file. The best way to set these flags in the toolchain file is like so:
# e.g. to use lld with Clang
set(CMAKE_EXE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_MODULE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_SHARED_LINKER_FLAGS_INIT "-fuse-ld=lld")
These three variables control the (default) set of linker flags for executables, loadable modules, and shared libraries, respectively. There is no need to handle CMAKE_STATIC_LINKER_FLAGS_INIT (for static libraries) here because the archiver is invoked, rather than the linker.
You can then set the toolchain file when you first run CMake by setting -DCMAKE_TOOLCHAIN_FILE=/path/to/toolchain.cmake at the command line. As of CMake 3.21, you will be able to pass --toolchain /path/to/toolchain.cmake instead (which is entirely equivalent, but a little less typing).
Set the variable ${CMAKE_LINKER} either in CMakeCache.txt or after ccmake . under advanced options.
I have to use CMAKE_CXX_LINK_EXECUTABLE, CMAKE_C_LINK_EXECUTABLE variable:
SET(CMAKE_C_LINK_EXECUTABLE "c:\\MoSync\\bin\\pipe-tool.exe")
I had success with doing
add_link_options("-fuse-ld=lld")
It is a variation on the previous answers here. The difference is the CMake command I use to set the flag.
Adding it to CMAKE_CXX_FLAGS has the disadvantage of then also having to add -Wno-unused-command-line-argument as the flags get also added to compilation commands, not only to linking ones.
The disadvantage of CMAKE_SHARED_LINKER_FLAGS is that you have to add it multiple times, to _SHARED_, _EXE_, and maybe I forgot something.
Here is a CMake function which sets linker based on some predefined arbitrary rules (Clang -> lld-version or lld, GCC -> gold).
The important parts:
Search for lld-version which matches the Clang compiler version (ex. lld-13 if Clang 13.x.x is used), falls back to lld if not found
add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR}")
Use all system threads when linker is set to gold:
add_link_options("-fuse-ld=gold;LINKER:--threads,--thread-count=${HOST_PROC_COUNT}")
The example is a bit too long because of comments, logs and custom logic, but it is self-contained and could be useful staring point for beginners.
function(select_best_linker) #lld for Clang and GNU gold for GCC
if (UNIX AND NOT APPLE)
include(ProcessorCount)
ProcessorCount(HOST_PROC_COUNT)
if(${CMAKE_CXX_COMPILER_ID} MATCHES Clang)
# By default LLD uses all system threads.
# This could be tweaked for versions 11+ (--threads=1), but cannot be disabled for older versions
# add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR};LINKER:--threads=${HOST_PROC_COUNT}") #LLD>=11
# add_link_options("-fuse-ld=lld;LINKER:--threads")#LLD <= 10 this is the default state
string(REPLACE "." ";" VERSION_LIST ${CMAKE_CXX_COMPILER_VERSION})
list(GET VERSION_LIST 0 CLANG_VERSION_MAJOR) #extract major compiler version
find_program(LLD_PROGRAM_MATCH_VER lld-${CLANG_VERSION_MAJOR}) #search for lld-13 when clang 13.x.x is used
find_program(LLD_PROGRAM lld) #else find default lld
if (LLD_PROGRAM_MATCH_VER) #lld matching compiler version
message(STATUS "Set linker to LLD (multi-threaded): ${LLD_PROGRAM_MATCH_VER}")
add_link_options("-fuse-ld=lld-${CLANG_VERSION_MAJOR}")
elseif(LLD_PROGRAM) #default lld
message(STATUS "Set linker to LLD (multi-threaded): ${LLD_PROGRAM}")
add_link_options("-fuse-ld=lld")
endif(LLD_PROGRAM_MATCH_VER)
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES GNU)
find_program(GNU_GOLD_PROGRAM gold)
if (GNU_GOLD_PROGRAM)
message(STATUS "Set linker to GNU gold: ${GNU_GOLD_PROGRAM}, using threads: ${HOST_PROC_COUNT}")
add_link_options("-fuse-ld=gold;LINKER:--threads,--thread-count=${HOST_PROC_COUNT}")
endif(GNU_GOLD_PROGRAM)
endif(${CMAKE_CXX_COMPILER_ID} MATCHES Clang)
endif(UNIX AND NOT APPLE)
endfunction(select_best_linker)
Tested on:
Ubuntu 20.04
CMake 3.16.3
GCC 9.4.0
Clang-12
Clang-13
GNU gold (GNU Binutils 2.37) 1.16
LLD 10.0.0 (compatible with GNU linkers)
Ubuntu LLD 13.0.1 (compatible with GNU linkers)
For completeness, another full-proof option is to just link /usr/bin/ld to ld.gold by running
sudo ln -sf /usr/bin/x86_64-linux-gnu-ld.gold /usr/bin/ld
as suggested here
There is another way to do it, gcc has a "-fuse-ld" option, you can set LINKER_FLAGS in CMakeLists.txt like these:
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fuse-ld=lld")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld")
then the custom specified linker should be invoked.