What happens if a static library (.a) contains duplicate object files (.o)?
AFAIK, the earlier version of Xcode was unable to link a static library if it was linked multiple times. I think there is some kind of duplicate file object or symbols problem.
I recently realized that Xcode5 no longer reports a related error in a duplicate static library link. Here's my test.
- I wrote 3 Objective-C classes called
s1, s2, s3
in split projects. - Each one is compiled into
s1.o, s2.o, s3.o
, - and finally zipped in
s1.a, s2.a, s3.a
. -
s2
connected (combined) withs1
, ands3
connected (combined) withs2
ands1
.
Finally, I got these files .a
.
Eonil$ ar -tv libs1.a
rw-r--r-- 501/20 64 Aug 3 18:38 2014 __.SYMDEF SORTED
rw-r--r-- 501/20 5528 Aug 3 18:38 2014 s1.o
Eonil$ ar -tv libs2.a
rw-r--r-- 501/20 120 Aug 3 18:38 2014 __.SYMDEF SORTED
rw-r--r-- 501/20 5872 Aug 3 18:38 2014 s2.o
rw-r--r-- 501/20 5528 Aug 3 18:38 2014 s1.o
Eonil$ ar -tv libs3.a
rw-r--r-- 501/20 224 Aug 3 18:38 2014 __.SYMDEF
rw-r--r-- 501/20 5872 Aug 3 18:38 2014 s3.o
rw-r--r-- 501/20 5528 Aug 3 18:38 2014 s1.o
rw-r--r-- 501/20 5872 Aug 3 18:38 2014 s2.o
rw-r--r-- 501/20 5528 Aug 3 18:38 2014 s1.o
All the same names as the files .o
are duplicated.
I wrote a project p1
which is a command line executable and linked it with everyone s1.a, s2.a, s3.a
. I was expecting some kind of duplication error, but it's just built and works well!
What happens in Xcode for duplicate links to static libraries?
source to share
Confirmed; the linker stops looking for symbols when it finds it in the first library.
If you use a parameter -all_load
, however, it doesn't work:
$ clang -all_load -o prog main.o -L. -lone -ltwo -lthree
duplicate symbol _func in:
./libone.a(file.o)
./libtwo.a(file.o)
duplicate symbol _func in:
./libone.a(file.o)
./libthree.a(file.o)
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
This was tested with C, but it doesn't matter:
$ cat main.c
extern void func();
int main(int argc, const char **argv)
{
func();
return 0;
}
$ cat file.c
#include <stdio.h>
void func()
{
printf("func()\n");
}
source to share