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

后端 未结 2 1904
我在风中等你
我在风中等你 2021-01-07 16:16

In the following example, the program should print \"foo called\":

// foo.c
#include 

__attribute__((constructor)) void foo()
{
    printf(\"         


        
2条回答
  •  隐瞒了意图╮
    2021-01-07 17:16

    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.

提交回复
热议问题