Why doesn't __attribute__((constructor)) work in a static library?

一笑奈何 提交于 2019-11-30 16:58:23

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;
}

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

As it was stated, unreferenced symbols from archive does not make it to the output binary, because linker discards them by default.

To override this behaviour when linking with static library, --whole-archive/--no-whole-archive options for the linker may be used, like this:

gcc -c main.c
gcc -c foo.c
ar rcs foo.a foo.o
gcc -o test -Wl,--whole-archive foo.a -Wl,--no-whole-archive main.o

This may lead to bloated binary, because all symbols from foo.a will be included by the linker to the output, but sometimes it is justified.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!