为什么`-finstrument-functions`对我不起作用?

com*_*fan 5 gcc

根据这个答案,它应该打印所有函数名称:

[root@ test]# cat hw.c
#include <stdio.h>

int func(void)
{  
  return 1;
}
int main(void)
{
  func();
  printf("%d",6);
  return 6;
}
[root@ test]# gcc -Wall hw.c -o hw -finstrument-functions
[root@ test]# ./hw 
6
[root@ test]# gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-48)
Copyright (C) 2006 Free Software Foundation, Inc.
Run Code Online (Sandbox Code Playgroud)

但为什么它不适合我呢?

小智 6

这是来自gcc手册:

-finstrument函数

生成用于进入和退出函数的检测调用.在函数输入之后和函数退出之前,将使用当前函数的地址及其调用站点调用以下分析函数.(在某些平台上,__ builtin_return_address不能超出当前功能,否则调用站点信息可能无法用于分析功能.)

void __cyg_profile_func_enter(void*this_fn,void*call_site);

void __cyg_profile_func_exit(void*this_fn,void*call_site);

除非somthing实现这些功能,否则会出现链接器错误(MinGW会发生这种情况).可以想象,您的GCC版本提供了空实现.

我通过提供这个实现让它与MinGW GCC合作:

#include  <stdio.h>

void __cyg_profile_func_enter (void *this_fn, void *call_site) {
    printf( "entering %p\n", this_fn );
}

void __cyg_profile_func_exit (void *this_fn, void *call_site) {
    printf( "leaving %p\n", this_fn );
}
Run Code Online (Sandbox Code Playgroud)

但这只给出了函数地址.我原以为应该有一个GCC默认的实现,但似乎没有.

人们也可能对调用树的这种可视化感兴趣,它使用-fintrument-functions标志 - 警告,我自己没有尝试过.

  • 你必须分别编译我给出的代码,如C代码,*不带*-finstrument-functions标志,然后将生成的.o文件与你的代码链接起来.这适用于MingW GCC 4.5.1,但我无法保证其他平台. (2认同)
  • ...或者您可以将 `__attribute__((no_instrument_function))` 添加到 `__cyg_profile_func_XXX` 函数的声明中,而不是单独编译,这将停止 `-finstrument-functions` 检测仪器。 (2认同)