If I have a class named ClassA in my main project, and I have a sub project built for a static library, in this sub project a class also named ClassA. I'm wonder that I can build and run successfully, how the compiler distinguish the two class?
-
4classes in libraries should be prefexed with something, just like UIView, NSMutableArray etc, this avoids conflicts such as these – Fonix Feb 05 '15 at 06:46
2 Answers
I think you are talking about how linker works.
The static library is a collection of several relocatable object files with the suffix ".o". The source files in your project are also compiled into a relocatable object files.
When linker works, it will resolve the symbols like ClassA
that used in your code. If it finds that in a relocatable object file - let's say rof1.o
, it would absorb rof1.o
into the executable file. The searching order of relocatable object file when linker try to resolve symbols determines which ClassA
is used. As the searching order is non-deterministic to us, you should use a different class name.
BTW if you set the other link flags to '-all_load', which indicates that the linker will try to combine all the relocatable object files into the executable file. Then if there are two or more same symbols, it will show an error "duplicated symbols".

- 6,912
- 1
- 24
- 53
-
-
@riyousan It seems like that according to a few times of test, but never depending on that. – KudoCC Feb 06 '15 at 00:56
-
I had tested in a demo, the result verify that conjecture,but you said right, we can't depending on that. Thanks a lot, and I think I should read some papers about ELF, your answer is very valuable to me. – riyousan Feb 06 '15 at 02:30
-
@riyousan I recommend you reading Chapter 7 Linking in this book "Computer Systems A Programmer's Perspective". – KudoCC Feb 06 '15 at 09:50
You need to rename one of your classes otherwise compiler throws an error when building your code.

- 49,246
- 17
- 84
- 119