25

I want to use libc++ together with clang on Arch Linux in CMake project. I installed libc++ and added following lines to CMakeLists.txt as said on LLVM site in Linux section of "Using libc++ in your programs":

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
set(CMAKE_EXE_LINKER_FLAGS "-lc++abi")

I have tried just "++abi" in linker's flags, but it didn't help. I need some help in figuring out what i should write in my CMakeLists.txt.

Ostrea
  • 262
  • 1
  • 4
  • 9

2 Answers2

32

Don't forget to set the compiler to clang++:

set(CMAKE_CXX_COMPILER "clang++")

Also, purge the cmake generated files (delete the folder CMakeFiles and CMakeCache.txt).

Depending on your system, it might also help to set

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++ -lc++abi")
xaxxon
  • 19,189
  • 5
  • 50
  • 80
emw
  • 344
  • 4
  • 3
  • 1
    Hmm, I get an error: The CMAKE_CXX_COMPILER: clang++ is not a full path and was not found in the PATH. Tell CMake where to find the compiler by setting either the environment variable "CXX" or the CMake cache entry CMAKE_CXX_COMPILER to the full path to the compiler, or to the compiler name if it is in the PATH. Not a big deal, I can set the compiler in the configuration. (I _don’t_ want to set the whole path.) – Flash Sheridan Oct 24 '18 at 19:49
  • I tried this method but still with linking error, complaining std::cout is undefined reference. – ChrisZZ Jun 12 '21 at 05:40
2

The "proper" way to do this in CMake at the moment, until a specific base feature is added to switch standard libraries that is, is to use a toolchain file.

In that toolchain file you specify the compiler etc similarly to the other answers here.

BUT what's great about toolchains is they can be swapped out quickly either on the commandline (using -DCMAKE_TOOLCHAIN_FILE=path/to/file) OR in VSCode with CMakeTools extension installed, and probably other editors too.

But having to hand code your own toolchain files is yet another obscure chore! No fun!

Luckily, I stumbled upon this github that maintains a suite of them so you don't have to write them from scratch! Should be a lot less likely to get them wrong.

https://github.com/ruslo/polly

Daniel Russell
  • 578
  • 4
  • 9