I am a newbie in Linux gcc. I am writing a simple code to learn the weak attribute in Linux gcc.
See my sample code:
weakref.c, the main file. I want to the file could work with or without foo method being defined.
#include <stdio.h>
extern void foo(void) __attribute__((weak));
int main() {
if (foo){
foo();
printf ("foo is defined\n");
} else {
printf("foo is not defined\n");
}
}
so, I run the following command to compile it and run it:
gcc weakref.c -o main_static
./main_static
and the output is "foo is not defined", which is what I expected.
Then I created a new file libfoo.c, see below:
#include <stdio.h>
void foo() {
printf("Print in foo.\n");
}
I attempted 3 ways to try to make main file work with the libfoo.c:
- Compile the libfoo.c and weakref.c and link the object files.
- Compile the libfoo.c as a static library, and link it with the object file of weakref.c
- Compile the libfoo.c as a shared library, and link it with the object file of weakref.c
Only the 3rd way works and get the following output:
Print in foo.
foo is defined
Could you please let me know if the weak ref only works with a shared library, and why? Thanks a lot!