c++ - gcc used 属性的用例是什么?

标签 c++ c gcc clang icc

#include <stdio.h>

// xyz will be emitted with -flto (or if it is static) even when
// the function is unused

__attribute__((__used__))
void xyz() {
  printf("Hello World!\n");
}

int main() {
  return 0;
}

我需要这个做什么?

除了直接调用函数之外,还有什么方法可以到达 xyz 吗,比如一些 dlsym() 之类的魔法?

最佳答案

Attribute used 在您想要强制编译器发出符号的情况下很有用,而通常情况下它可能会被省略。作为GCC's documentation说(强调我的):

This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

例如,如果您有如下代码:

#include <iostream>

static int foo(int a, int b)
{
    return a + b;
}

int main()
{
   int result = 0;

   // some inline assembly that calls foo and updates result

   std::cout << result << std::endl;
}

您可能会注意到,-O 标志(优化级别 -O1)没有符号 foo:

g++ -O -pedantic -Wall check.cpp -c
check.cpp:3: warning: ‘int foo(int, int)’ defined but not used
nm check.o | c++filt | grep foo

因此,您不能在此(假想的)内联程序集中引用 foo

通过添加:

__attribute__((__used__))

它变成了:

g++ -O -pedantic -Wall check.cpp -c
nm check.o | c++filt | grep foo
00000000 t foo(int, int)

因此现在可以在其中引用 foo

您可能还发现 gcc 的警告现在消失了,因为您已经告诉编译器您确定 foo 确实在“幕后”使用".

关于c++ - gcc used 属性的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31637626/

相关文章:

c++ - 使用 GCC 10 泄漏的简单协程

c++ - 从多个线程调用 C 文件中的函数

c++ int访问器返回0,即使mutator设置正确

c++ - QSqlTableModel::setData() 对于 Qt::EditMode 也返回 false

C- 可能的内存泄漏?

c++ - 使用意外声明为函数的对象后解释 GCC 错误

c - GCC 动态链接 libc static 和其他一些库,重新访问了吗?

c++ - 如何在 QML 中访问 C++ 类对象而不是在 QML 中创建单独的对象?

c - 为什么我会遇到此代码的段错误?应该很简单?

c - 数组不溢出(C语言)