2011-05-30 201 views
5

this answer,它應該打印所有的函數名稱:爲什麼'-finstrument-functions`不適合我?

[[email protected] test]# cat hw.c 
#include <stdio.h> 

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

但爲什麼它不是爲我工作?

+0

答案是錯的。 – 2011-05-30 12:37:27

回答

5

這是從GCC手冊:

-finstrument函數

產生 入口和出口功能的儀器調用。在功能輸入之後和在 函數退出之前,只有 函數將被調用,當前函數的 地址和其調用地點的 。 (在某些平臺上, __builtin_return_address不會超出當前FUNC-重刑工作,所以 調用位置信息可能不 可供分析函數 否則)

無效__cyg_profile_func_enter(void *的this_fn,無效* call_site );

空隙__cyg_profile_func_exit(無效* this_fn,無效* call_site);

除非somthing實現這些功能,否則您將收到鏈接器錯誤(這是發生在MinGW上的錯誤)。可以想象,你的GCC版本提供了空白的實現。

我得到它通過提供此實現與MinGW的海灣合作委員會的工作:

#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); 
} 

但這只是給出了函數的地址。我原以爲應該有一個GCC的默認實現這個,但似乎沒有。

的人也可能有興趣在this visualisation of the call tree,它使用-fintrument-功能標誌 - 警告,我還沒有嘗試過自己。

+0

@Neil Butterworth,我可以手動將這兩個函數添加到我的'.c'文件中嗎? – 2011-05-30 12:43:37

+0

你可以,但實施它們是相當複雜的。 – 2011-05-30 12:44:24

+0

@Neil Butterworth,我只是想讓它打印函數名稱,爲什麼它很複雜? – 2011-05-30 12:47:06

1

您並未實際執行任何檢測。 -finstrument-functions開關只是告訴gcc在進入和退出每個函數時調用某個函數。但是你必須自己定義這些函數(通常這是通過鏈接一個profiler庫來完成的)。

+0

需要採取哪些額外步驟才能使用'-finstrument-functions'開關?我希望儘可能最小化...... – 2011-05-30 12:41:02

+0

@ compile-fan:[documentation](http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-finstrument_002dfunctions-2168)提到了必須實施的兩個功能。我不知道是否有現成的圖書館使用它們。 – 2011-05-30 14:14:10

0

編碼__cyg_profile_func_enter和__cyg_profile_func_exit並不複雜。最簡單的解決方案是確保上述功能將地址詳細信息寫入文件,並有一個獨立的過程從文件中讀取地址並使用可執行文件的符號表解析它們。如果您嘗試在函數本身中執行地址解析,則可能需要一些時間。

我碰到下面的文章來 - http://balau82.wordpress.com/2010/10/06/trace-and-profile-function-calls-with-gcc/

其中採用addr2line從binutils的用於這一目的。檢查這有助於你

+0

有時..只是爲了調試正確性而打印fn名稱真的很有用 – kchoi 2016-07-28 22:19:06

0

一個實現你在找什麼,提供here

+0

對我而言不起作用:-(https://github.com/elcritch/etrace/issues/3 – 2017-11-05 11:07:43