我正在寻找一种方法来自动将代码添加到函数的开头和开头。这个想法是我想稍后分析正在运行的代码。例如我有以下功能:
void helloWorld(){
printf("Hello World!\n");
}
void worldHello(){
printf("World hello!\n");
}
我想要某种宏来将它们扩展为:
void helloWorld(){
printf("Function id 1 enter");
printf("Hello World!\n");
printf("Function id 1 exit");
}
void worldHello(){
printf("Function id 2 enter");
printf("World hello!\n");
printf("Function id 2 exit");
}
每次我使用我的宏时,id 都是唯一的。任何人对我如何实现这一点有什么好主意吗?我查看了 GCC 中的“__COUNTER__”,但并没有真正按照我的意愿让它工作。
最佳答案
如果您使用的是 GCC,请查看 -finstrument-functions
开关 - 参见 https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-finstrument-functions它基本上在进入和离开任何被调用的函数时调用用户定义的函数。这有一些优点:
- 您根本不需要修改您的功能。
- 无论函数如何退出,您的代码都会被调用(您的函数中可以有任意数量的
return
,并不关心)
关于c - 在 c 中的函数开始和结束处添加唯一代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38714082/