将图书馆最后一个链接到所有目标

将图书馆最后一个链接到所有目标

本文介绍了将图书馆最后一个链接到所有目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中添加对gperftools的支持以配置cpu和内存。 Gperftools需要为每个二进制文件连接最后的库tcmalloc。



有一种方法与cmake附加库到每个二进制目标我的项目不需要编辑每个



CMakeLists.txt

  #假设附加库的路径是< 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)
}

假设例如附加库替换 malloc 函数,可执行文件将使用替换。



在Linux上使用CMake 2.8和3.4测试

更新



根据@Falco的建议,如果 gcc 编译器附加库可以指定 -l:前缀:

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

gcc 将使用其完整路径将可执行文件与给定库链接,因此可执行文件将在没有其他RPATH设置的情况下工作。


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:

  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.

这篇关于将图书馆最后一个链接到所有目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 10:51