Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

// foo.c #include <stdio.h>  __attribute__((constructor)) void foo() {     printf("foo called\n"); }  // main.c int main() {     return 0; } 

If the program is compiled like this, it works:

gcc -o test main.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 

Why does this happen?

like image 842
Jay Conrod Avatar asked Jul 29 '09 19:07

Jay Conrod


1 Answers

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 
like image 172
Jay Conrod Avatar answered Oct 13 '22 07:10

Jay Conrod