为什么 __attribute__((constructor)) 不能在静态库中工作? [英] Why doesn't __attribute__((constructor)) work in a static library?
问题描述
在下面的例子中,程序应该打印foo called
"
:
In the following example, the program should print "foo called
"
:
// foo.c
#include <stdio.h>
__attribute__((constructor)) void foo()
{
printf("foo called
");
}
// main.c
int main()
{
return 0;
}
如果程序是这样编译的,它可以工作:
If the program is compiled like this, it works:
gcc -o test main.c foo.c
但是,如果 foo.c 被编译成静态库,则程序不会打印任何内容.
However, if foo.c is compiled into a static library, the program prints nothing.
gcc -c main.c
gcc -c foo.c
as rcs foo.a foo.o
gcc -o test foo.a main.o
为什么会这样?
推荐答案
链接器不会在最终程序中包含 foo.a 中的代码,因为 main.o 中没有任何内容引用它.如果main.c
改写如下,程序就可以工作了:
The linker does not include the code in foo.a in the final program because nothing in main.o references it. If main.c
is rewritten as follows, the program will work:
//main.c
void foo();
int main()
{
void (*f)() = foo;
return 0;
}
此外,当使用静态库进行编译时,gcc(或链接器)的参数顺序很重要:库必须位于引用它的对象之后.
Also, when compiling with a static library, the order of the arguments to gcc (or the linker) is significant: the library must come after the objects that reference it.
gcc -o test main.o foo.a
这篇关于为什么 __attribute__((constructor)) 不能在静态库中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!