When debug the function symbols conflicts problem, I find a strange behavior of gcc i couldn't understand, illustrate by the following sample code:
main.c
#include <stdio.h>
int main()
{
b();
a();
}
a.c
#include <stdio.h>
void a(void)
{
printf("func a in a\n");
}
b.c
#include <stdio.h>
void a()
{
printf("func a in b\n");
}
void b()
{
printf( "func b try to call a \n");
a();
}
compile:
gcc -c a.c
gcc -c b.c
ar -cr liba.a a.o
ar -cr libb.a b.o
gcc main.c liba.a libb.a
execute:
./a.out
func b try to call a
func a in b
func a in b
My question is :
- Why calling function
ainmainfunction isa in b.cinstead ofa in a.c? - After change the library order:
gcc main.c libb.a liba.a, the result is the same. Why? - Why the linker don't report symbol conflict in this situation?
Object files are searched for symbols to be resolved in the order of the object files' appearances, left to right, in the options passed to the linker.
Assumed the following had been run in preparation to linking:
Then this
would produce:
The linker did the following:
main.oneedsa()andb (). Firstlibais searched:a()is found,b()isn't. So secondlylibbis searched.b()is found, but also anothera()leading to the linker error shown above.If doing:
No errors are given and
mainis created.The linker did the following:
main.oneedsa()andb (). Firstlibbis searched:a()andb()are is found. As there is nothing to resolve any morelibblibaisn't even looked at/in.In the latter case the program's (
main's) output is:What the linker would do/show for all other possible permutation of
main.o,liba.aandlibb.ais left as an exercise to the reader. ;-)