83

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
set(CMAKE_C_COMPILER   xgcc.exe)
set(CMAKE_CXX_COMPILER xgcc.exe)

11 Answers 11

52

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!

Edit: nicer approaches to customizing this behaviour can be found in answers from usr123467 and FeRD.

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.

12
  • 1
    How to define OBJECTS in -DCMAKE_CXX_LINK_EXECUTABLE="<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" ?
    – Ezio
    Commented Mar 24, 2017 at 6:07
  • 3
    You don't specify anything in this rule. It's a rule for cmake to follow to build an executable, so it inserts the objects that got built from eg sources you added to targets in your CMakeLists.txt files.
    – mabraham
    Commented Mar 24, 2017 at 6:44
  • 1
    @mabraham Overriding CMAKE_CXX_LINK_EXECUTABLE confuses CMake and it doesn't provide the object file on the initial testing of linking a sample C application. I'm getting "The C compiler ... is not able to compile a simple test program. clang++: error: no input files". Maybe this is what Ezio meant with his 1st comment. CMake version: 3.12.4. See also cmake.org/pipermail/cmake-developers/2014-June/022364.html Commented Mar 19, 2020 at 9:22
  • 1
    Here's the CMake source code of setting the default value of CMAKE_CXX_LINK_EXECUTABLE. I don't know why it does not use CMAKE_LINKER though.
    – cyfdecyf
    Commented Mar 5, 2022 at 8:23
  • 1
    This answer relies on undocumented implementation details. See gitlab.kitware.com/cmake/cmake/-/issues/24990. CMake 3.29 now provides an official solution to the original problem.
    – jpr42
    Commented May 9 at 0:51
44

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

  1. 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 a limited set of possible arguments. (They're listed in the gcc --help=common output, as of GCC 12.2.1 the list is: bfd, gold, lld, or mold.) 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.)

14
  • 4
    Of all the "solutions" presented here, this is the only command-line solution that actually worked for me (cmake 3.19.2)
    – sdenham
    Commented Dec 29, 2020 at 15:36
  • 1
    Wait, this isn't the best idea, right? After all this flag won't be used unless the compiler driver is used to link some binary. @sdenham there are so many CMake projects out there all with subtle differences, whether this works or not depends very much on your project. Should work on most barebones/vanilla projects, though. Commented Jan 21, 2021 at 15:45
  • 3
    @0xC0000022L I agree that it is not an ideal solution, but for anyone finding this question, as I did, because the CMake project they are trying to use does rely on the compiler driver to invoke the linker, this may be the best of all solutions proposed here.
    – sdenham
    Commented Jan 21, 2021 at 22:30
  • 4
    @FeRD Nope, my point is that this is the wrong variable to set. It will work, don't get me wrong. But every single compilation unit being compiled will cause a warning of an unused command line switch. Because that switch is really only ever relevant during the linking step. So while this works it can hardly be called a best practice. In a GNUmakefile you wouldn't use CXXFLAGS to convey linker flags, typically. Regardless, I upvoted for the general utility of this answer, despite this flaw. Commented Jan 22, 2021 at 23:43
  • 3
    @FeRD Ah, but there is. It's just that you have to do it for every single type of artifact you're linking. CMAKE_EXE_LINKER_FLAGS and CMAKE_SHARED_LINKER_FLAGS are two of them 😉 Commented Jan 23, 2021 at 0:07
17

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.

7
  • 1
    This is the right solution. No long, error-prone command lines. cmake -DCMAKE_CXX_FLAGS="-fuse-ld=lld" as suggested above would be a good solution if it didn't cause an error while compiling (not linking) with -Werror, since the flag is unused during compilation.
    – swineone
    Commented Aug 12, 2021 at 18:40
  • There are also both CMAKE_MODULE_LINKER_FLAGS and CMAKE_STATIC_LINKER_FLAGS, for completeness' sake. And then of course potentially separate CMAKE_SHARED_LINKER_FLAGS_DEBUG, CMAKE_SHARED_LINKER_FLAGS_RELEASE, etc... though I don't know what possible advantage there would be to modifying the linker for only some configurations.
    – FeRD
    Commented Aug 30, 2021 at 11:19
  • 1
    This answer depends on the right compiler. Setting the linker has a different syntax for GCC and Clang.
    – usr1234567
    Commented Mar 12, 2022 at 21:09
  • 1
    @user7610 Best add LINK_OPTIONS to the list (which supersedes LINK_FLAGS). As this can be used in CMakePresets.json (at cacheVariables).
    – Dominik
    Commented Dec 22, 2023 at 16:21
  • 2
    Thanks for the hint. CMake keeps improving and I am missing all the changes. Thankfully, with CMake 3.29 this issue will be gone: stackoverflow.com/a/77304927/2799037
    – usr1234567
    Commented Dec 23, 2023 at 13:11
16

Beginning with version 3.29, CMake offers a way to set the linker.

  • Set the variable CMAKE_LINKER_TYPE to one of the predefined variables LLD, GOLD, MOLD, BFD, MSVC, or the more exotic ones. For more details have a look into the documentation.
  • If the presets are not enough, you can set CMAKE_<LANG>_USING_LINKER_<TYPE> with either the path to the linker or the flag for the compiler. Tell CMake your choice by setting the variable CMAKE_<LANG>_USING_LINKER_MODE (Documentation).
11

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

1
  • 1
    Thanks, also for the explanatory notes, I was looking for that.
    – Bart
    Commented Oct 23, 2023 at 14:40
6

I have to use CMAKE_CXX_LINK_EXECUTABLE, CMAKE_C_LINK_EXECUTABLE variable:

SET(CMAKE_C_LINK_EXECUTABLE "c:\\MoSync\\bin\\pipe-tool.exe")
1
  • 29
    This doesn't work in most cases - that variable establishes the rule for the whole link command, and generally flags and arguments will be required for linking.
    – mabraham
    Commented Aug 12, 2014 at 21:27
4

Set the variable ${CMAKE_LINKER} either in CMakeCache.txt or after ccmake . under advanced options.

8
  • 1
    Can I set it in CMakeLists.txt? I 've just looked for CMAKE_LINKER in the cmake man page but I cannot find it. Are You sure about the name of the variable?
    – Breezeight
    Commented Dec 8, 2009 at 16:56
  • 2
    Yes. Invoke ccmake . in your build directory and press 't'. Scroll down until you hit CMAKE_LINKER. Commented Dec 8, 2009 at 22:53
  • Sure but when I compile the project for the first time I start with cmake -DCMAKE_TOOLCHAIN_FILE=MyToolchain.cmake . And this generate an error.
    – Breezeight
    Commented Dec 9, 2009 at 9:34
  • 2
    I used to do exactly this, and now it doesn't work. As if cmake doesn't look at this variable at all: setting CMAKE_LINKER to complete nonsense doesn't change the error (or the command-lines) in the slightest. CMake 3.14.5.
    – ulidtko
    Commented Sep 19, 2019 at 17:31
  • 1
    @mabraham one example of when it can be a feature is when the compile flag requires linking with a run-time library (e.g. fsanitize)
    – pooya13
    Commented Feb 1, 2020 at 10:05
3

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

1
  • This works nicely. You can do the same with llvm's lld, and it's shown as an option in the official docs too: ln -s /path/to/ld.lld /usr/bin/ld lld can also be faster and use less memory than gold
    – Arghnews
    Commented May 7 at 20:04
3

Here is a CMake function which sets linker based on some predefined arbitrary rules (Clang -> lld-version or lld, GCC -> gold).

The important parts:

  1. 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}")
  1. 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)
2

Finally, implemented in CMake 3.29 via CMAKE_<LANG>_USING_LINKER_<TYPE>.

A custom linker type can be defined, usually in a toolchain file:

set(CMAKE_LINKER_TYPE lld_launcher)
set(CMAKE_C_USING_LINKER_lld_launcher "-fuse-ld=/path/to/lld-launcher.sh")
set(CMAKE_C_USING_LINKER_MODE FLAG)
3
  • CMake 3.29 isn't released at the time of writing (I guess that's why someone downvoted you?) but -DCMAKE_LINKER_TYPE=LLD looks promising. Commented Jan 9 at 16:50
  • @MichaelPlatings aye, iff you have only one LLD installed :) Commented Jun 27 at 17:40
  • Okay, this sort-of-works for me, although, honestly, I'd prefer a different syntax. The good news is that CMake 3.29 does, indeed, respect those variables, even when passed on the command line. My issue is just that I'm comparing compilations using two different clang versions, and need to switch them on demand, using the same project. Granted, there are other ways of accomplishing the same (using a special flag on the CLI, but, in the many configuration files, set up different linkers according to that special flag). But I like to keep the CMakeFiles unpolluted :) Commented Jun 27 at 17:44
0

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.

1
  • Note that GCC has very precise limitations on what linkers it can use or not; Clang is more flexible, even allowing whole pathnames to specific linkers. Clang, however, also recognises the GCC flags and interprets them in the same way as GCC; it just happens to allow many more alternatives ;) Commented Jun 27 at 17:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.