Using LLVM linker when using Clang & CMake

clang, cmake, linker

Solution

This turns out to be unrelated to CMake: `clang++` uses the system linker by default. For example,

echo "#include <atomic>\n int main() { return 0; }" \
    | clang++ -x c++ -std=c++11 -stdlib=libc++ -

uses `/usr/bin/ld` to link the application. To change the linker to `llvm-link`, one needs to first emit LLVM byte code, and then call the linker, e.g.:

echo "#include <atomic>\n int main() { return 0; }" \
    | clang++ -x c++ -std=c++11 -stdlib=libc++ -S -emit-llvm -o - - \
    | llvm-link -o binary -

This bypasses `/usr/bin/ld`.

Problem

What's the best way to tell CMake to use the LLVM linker `llvm-link` instead of GNU `ld` as linker? When configuring a project with ``` CXX=clang++ cmake <args> ``` the default linker appears to be untouched, remaining `usr/bin/ld` (on Linux). Is this possible without using a separate toolchain file?

Original source

Related problems