I'm adding support for gperftools in my project to profile the cpu and memory. Gperftools needs the library tcmalloc to be linked last for each binary.
Is there a way with cmake to append a library to every binary targets of my project without having to edit each CMakeLists.txt
?
I've found a similar question here: link library to all targets in cmake project, but it does not answered. It is suggested to overcome the problem using macros, but it is not explained how this could be achieved.
As @Florian suggested, you can use CMAKE_CXX_STANDARD_LIBRARIES variable for library which should be linked to every target as system, so it will be effectively last in link list.
There are a couple of things with this variable:
Unlike to what is written in CMake documentation, the variable's name contains
<LANG>
prefix.While using this variable expects full path to the additional library, in case that additional library is not under LD_LIBRARY_PATH, executable will not work with
Cannot open shared object file error
error. For me, withC
compiler (and corresponded prefix in the variable's name),link_directories()
helps. WithC++
, only RPATH setting helps.Example:
CMakeLists.txt:
hello.cpp:
Assuming, e.g., that additional library replaces
malloc
function, executable will use that replacement.Tested with CMake 2.8 and 3.4 on Linux (Makefile generator).
Update:
As suggested by @Falco, in case of
gcc
compiler additional library can be specified with-l:
prefix:With such prefix
gcc
will link executable with given library using its full path, so the executable will work without additional RPATH settings.