c++ - 是否可以在定义函数的位置之外声明函数的属性? (海湾合作委员会)

标签 c++ c gcc function-attributes

在 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.hbar.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/

相关文章:

c - C 中表达式必须具有常量值

c++ - 给定大小 N 和类型 T 生成元组的函数

c++ - Visual Studio 没有为静态库构建创建 .lib 文件

c++ - 这种语法是非法的吗?

c++ - 数据被添加到 curl 的检索内容中

c - C 中的位设置/清除?

c - PIC16F628计数器坏了?

c++ - 在 GitHub 上编译 TinyMT 时隐式声明的 ‘...’ 已弃用 [-Wdeprecated-copy]

c++ - C++中引用变量的地址

c - 辛科斯去哪儿了? (海湾合作委员会c)