如何告诉gcc使用我自己的函数调用每个_line_代码来检测代码?

例如,有来源:

void my_special_debugging_function(const char* function_name, const char* file_name, int line_number); void func1() { func3(); func4(); } void foo() { func1(); if(qqq) { func2(); }; func3(); func4(); for(...) { func5(); } } 

它应编译为:

 void my_special_debugging_function(const char* function_name, const char* file_name, int line_number); void func1() { my_special_debugging_function("func1", "prog.c", 3); func3(); my_special_debugging_function("func1", "prog.c", 4); func4(); my_special_debugging_function("func1", "prog.c", 5); } void foo() { my_special_debugging_function("foo", "prog.c", 8); func1(); my_special_debugging_function("foo", "prog.c", 9); if(qqq) { my_special_debugging_function("foo", "prog.c", 10); func2(); my_special_debugging_function("foo", "prog.c", 11); }; my_special_debugging_function("foo", "prog.c", 12); func3(); my_special_debugging_function("foo", "prog.c", 13); func4(); my_special_debugging_function("foo", "prog.c", 14); for(...) { my_special_debugging_function("foo", "prog.c", 15); func5(); my_special_debugging_function("foo", "prog.c", 16); } my_special_debugging_function("foo", "prog.c", 17); } 

当然,my_special_debugging_function应该能够使用backtracefunction。

有没有选择gcc来做到这一点? 或者是否有工具在源代码级别执行此操作? (例如,用我的函数生成其他C源)

@related 如何用我的字符串“交错”C / C ++源(只在适当的地方内部函数)?

@related 我应该使用什么样的探查器来测量_real_ time(包括等待系统调用)花在这个函数上,而不是_CPU_ one

请参阅GCC文档中的-finstrument-functions 。 您可能希望在调试函数中使用dladdr() ,这可能还需要与-Wl,-export-dynamic

如果您使用的是gcc版本> = 4.5,您可以编写一个gcc插件 ,以您喜欢的方式处理AST。 但该解决方案将依赖于编译器。

您还可以从eclipse CDT获取AST并从该输入重新生成C代码。

正如另一个答案所述, I don't think that there is any way to tell GCC to do that, without preprocessor tricks and edits to the source code. – nategoose I don't think that there is any way to tell GCC to do that, without preprocessor tricks and edits to the source code. – nategoose

您可以使用aspectc ++轻松完成。 从aspectc.org获取此编译器这是一个满足您需求的简单方面。 Trace.ah

 #ifndef __trace_ah__ #define __trace_ah__ #include  #include  using namespace std; template  struct ArgPrinter { template  static inline void work (JP &tjp) { ArgPrinter::work (tjp); cout << *tjp.template arg () << " "; } }; template <> struct ArgPrinter<0> { template  static inline void work (JP &tjp) {} }; aspect trace { int depth=-1; pointcut virtual methods() = "% ...::%(...)"; template  void print_args (JP &tjp) { ArgPrinter::work (tjp); } advice execution (methods()) : before () { depth++; cout << "Enter -> " << JoinPoint::signature() <<" Depth:"<arg(0); print_args (*tjp); cout<<")"<result(); cout << "Exit <- " << tjp->signature()<< " Depth: "<signature()<< " Depth: "< 

使用ac ++编译器在项目中编译此方面然后运行程序。 然后你应该在控制台中看到跟踪。 快乐的追踪!