在 GCC 中,许多函数属性可用于为编译器提供语法,以对代码进行有用的优化/分析。
有用的链接:https://www.acrc.bris.ac.uk/acrc/RedHat/rhel-gcc-en-4/function-attributes.html
例如,函数属性的典型用法如下所示:
// foo.h
__attribute__((no_instrument_function)) void foo();
// test.c
// gcc -finstrument-functions test.c -o test
#include <stdio.h>
#include "foo.h"
void foo() { printf("Foo\n"); }
int main() { foo(); return 0; }
编译上述代码将在main
函数中仅插入__cyg_profile_func_enter
和__cyg_profile_func_exit
,并避免将它们插入foo
。
现在我想知道是否可以在单独的文件中声明目标函数的函数属性。
例如,如果我有 foo.h
和 bar.h
没有属性,有没有办法拥有单个文件为 foo 和 bar 函数提供属性?
例如,我尝试通过执行以下操作来解决这个问题(错误的解决方案):
// attributes.c
void foo() __attribute__((no_instrument_function));
void bar() __attribute__((no_instrument_function));
// bar.h
void bar();
// foo.h
void foo();
// test.c
// gcc -finstrument-functions attributes.c test.c -o test
#include <stdio.h>
#include "foo.h"
#include "bar.h"
void foo() { printf("Foo\n"); }
void bar() { printf("Bar\n"); }
int main() { foo(); return 0; }
我尝试解决此问题的用例或原因是,与这些微基准不同,我尝试将函数属性应用于具有许多源/头文件的更大程序。换句话说,我希望为分布在不同文件中的许多函数声明许多函数的函数属性,并且我认为创建一个文件并将其插入到 Makefile 中要容易得多>.
我想我可以创建一个脚本来扫描文件夹并自动(使用正则表达式)或通过插入代码手动添加属性。尽管如此,我仍在探索是否有一个更干净的解决方案来解决这个问题。预先感谢您!
最佳答案
GCC 文档显示“Compatible attribute specifications on distinct declarations of the same function are merged. ” 这意味着您可以在一个声明中(例如翻译单元中的第一个声明)声明一个属性,并在后面的声明(包括函数定义)中省略它,该属性将合并到后面的声明中。
但是,您不能像处理 attribute.c
那样,仅仅将它们放入单独的源代码文件中,然后将它们与其他源代码分开编译。编译器在编译受该属性影响的源代码时必须看到该属性。您可以将它们放入名为 attribute.h
的文件中,然后将 attribute.h
包含在其他头文件中。
关于c++ - 是否可以在定义函数的位置之外声明函数的属性? (海湾合作委员会),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75771789/