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
实际上是在"幕后"使用的.