gcc使用属性的用法是什么?

Tho*_*mas 7 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;
}
Run Code Online (Sandbox Code Playgroud)

我需要什么呢?

xyz除了直接调用函数之外,还有什么方法可以达到某种程度,比如dlsym()像魔法一样?

Grz*_*ski 12

used当您希望强制编译器发出符号时,属性很有用,通常可以省略它.正如GCC的文件所述(强调我的):

附加到函数的此属性意味着即使看起来函数未被引用,也必须为函数发出代码.例如,仅在内联汇编中引用该函数时,这很有用.

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

你可能会注意到,没有符号foo存在与-O标志(优化级-O1):

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
Run Code Online (Sandbox Code Playgroud)

因此,您无法foo在此(虚构的)内联汇编中引用.

通过增加:

__attribute__((__used__))
Run Code Online (Sandbox Code Playgroud)

它变成了:

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

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

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

  • 另一个用例,尤其是在C ++中,用于调试助手。例如,您可能有一个`void dump()`方法,用于漂亮地打印内部对象。您不会在程序中的任何位置调用它,但是希望在调试器中暂停时可以调用它。__attribute __((used))将确保不会将其删除为无效代码。 (2认同)