#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/