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

后端 未结 2 1924
我在风中等你
我在风中等你 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:18

    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
    

提交回复
热议问题