What's the order for gcc to link unresolved symbol in static library

1.6k views Asked by At

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 a in main function is a in b.c instead of a 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?
2

There are 2 answers

6
alk On BEST ANSWER

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:

gcc -c main.c
gcc -c a.c
gcc -c b.c
ar -cr liba.a a.o
ar -cr libb.a b.o

Then this

gcc -o main main.o liba.a libb.a

would produce:

libb.a(b.o): In function `a':
b.c:(.text+0x0): multiple definition of `a'
liba.a(a.o):a.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status

The linker did the following:

main.o needs a() and b (). First liba is searched: a() is found, b() isn't. So secondly libb is searched. b() is found, but also another a() leading to the linker error shown above.

If doing:

gcc -o main main.o libb.a liba.a

No errors are given and main is created.

The linker did the following:

main.o needs a() and b (). First libb is searched: a() and b() are is found. As there is nothing to resolve any more libb liba isn't even looked at/in.

In the latter case the program's (main's) output is:

func b try to call a  
func a in b
func a in b

What the linker would do/show for all other possible permutation of main.o, liba.a and libb.a is left as an exercise to the reader. ;-)

2
zaadeh On

You are not including a and b function declarations in main.c. if you do, you will get multiple declaration error from compiler, before it is passed to linker. You must be doing something wrong in main.c.