Link a library as last against all targets

2020-03-05 03:32发布

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.

标签: c++ cmake
1条回答
▲ chillily
2楼-- · 2020-03-05 03:42

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:

  1. Unlike to what is written in CMake documentation, the variable's name contains <LANG> prefix.

  2. 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, with C compiler (and corresponded prefix in the variable's name), link_directories() helps. With C++, only RPATH setting helps.

Example:

CMakeLists.txt:

# Assume path to the additional library is <a-dir>/<a-filename>
set(CMAKE_CXX_STANDARD_LIBRARIES <a-dir>/<a-filename>)
set(CMAKE_INSTALL_RPATH <a-dir>)

add_executable(hello hello.cpp)
install(TARGETS hello DESTINATION bin)

hello.cpp:

#include <stdlib.h>
int main(void)
{
    void p = malloc(10);
    if(p) free(p);
}

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:

set(CMAKE_CXX_STANDARD_LIBRARIES -l:<full-library-path>)

With such prefix gcc will link executable with given library using its full path, so the executable will work without additional RPATH settings.

查看更多
登录 后发表回答