Ubuntu 11.10 链接 perftools 库

nko*_*nig 6 c c++ ubuntu linker

我无法在 Ubuntu 11.10 中获得 gcc 以在 google perftools -lprofiler 中正确链接。问题似乎是链接器丢弃了未在程序中直接使用的库。

一个例子会有所帮助。

我们称之为 main.cpp:

#include <math.h>

int main()
{
  double value;
  for (int i=0; i < 1000000; i++)
  {
    for (int j=0; j < 1000; j++)
      value = sqrt(100.9);
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译使用:

g++ -c main.cpp -o main.o
g++ main.o -o main -lm -lprofiler
Run Code Online (Sandbox Code Playgroud)

使用 ldd ./main 检查可执行文件:

  linux-vdso.so.1 =>  (0x00007fff5a9ff000)
  libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f32bc1c9000)
  /lib64/ld-linux-x86-64.so.2 (0x00007f32bc593000)
Run Code Online (Sandbox Code Playgroud)

通常,我会运行:

CPUPROFILE=/tmp/profile ./main
Run Code Online (Sandbox Code Playgroud)

生成配置文件输出。但由于配置文件库未链接,因此不会生成配置文件输出。

我确保分析器库在我的搜索路径中,并尝试直接链接共享库和静态库。

上述测试在 Ubuntu 10.04、Ubuntu 10.10、Ubuntu 11.04、SUSE 12.1 和 Fedora 16 上运行良好。

此外,一旦我包含使用探查器的函数调用(例如 ProfilerStart() 和 ProfilerStop()),探查器库就会链接到可执行文件中。

关于如何让 gcc 链接到分析器库中的任何想法?

谢谢。

Emp*_*ian 6

g++ main.o -o main -lm -lprofiler
Run Code Online (Sandbox Code Playgroud)

正如 another.anon.coward 评论的那样,您很可能成为g++使用--as-needed链接器标志的受害者。试试这个:

g++ main.o -Wl,--no-as-needed -lprofiler -Wl,--as-needed
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. g++已经添加-lm,无需再次添加
  2. 重新开启很重要--as-needed。不这样做可能会导致您链接到您并不真正需要的其他库。