Link a library as last against all targets

后端 未结 1 1178
南方客
南方客 2021-01-06 11:51

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.

相关标签:
1条回答
  • 2021-01-06 12:17

    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.

    0 讨论(0)
提交回复
热议问题