Library conflicts in linux
Lib1.c
# Include <stdio. h>
Int fun ()
{
Printf ("lib1 \ n ");
Return 0;
}
Lib2.c
# Include <stdio. h>
Int fun1 ()
{
Return 0;
}
Int fun ()
{
Printf ("lib2 \ n ");
Return 0;
}
Test. c
# Include <stdio. h>
Int fun ();
Int fun1 ();
Int main ()
{
Fun1 ();
Fun ();
}
Generate libraries liblib1.a and liblib2.a
When the test is compiled in this way, gcc test. c-L.-llib2-llib1 will not encounter compilation errors.
While gcc test. c-L.-llib1-llib2
The following compilation error occurs:
./Liblib2.a (lib2.o): In function 'fun ':
Lib2.c :(. text + 0xa): multiple definition of 'fun'
./Liblib1.a (lib1.o): lib1.c :(. text + 0x0): first defined here
Collect2: ld returned 1 exit status
Because the implementation of ld is not very clear, I guess the following: Write the symbol table first, and then search for the symbols in the order of each database until all the symbols are satisfied, this prevents errors in the first case, but when locating a symbol, it is necessary to compare all the symbols in the symbol table with the symbols in the library, which leads to the second case, instead of continuing to search for symbols in the database that are no longer followed.
When you add another function named fun2 to two implementation files. c does not call fun2 and will also produce a redefinition error. Therefore, the comparison sequence is to compare the database with the symbol table, rather than the comparison between the symbol table and the database.