I'm working on Ubuntu Linux to build Android and Linux binary. I have a static library which has been linked by two shared libraries, and there is a global object in the static library.
By my understanding, the global object will be exist in both *.so
, and will cause issues because the function symbols in each shared library access different global variables.
(I referred the static library in the command line when building both shared libraries. I have been using -Wl,--whole-archive
and -Wl,-z,defs
switches. So the shared library contains the symbols of the static library.)
So the question is:
-----------------Edit 1-----------------------
As R Soha said we shouldn't have status in static library, or should provide an shared library.
And I think it is bad and sad to have this limitation: Static library should not have status or should be provide as an shared libraries.
The reason is: 1. The global variable is common used, for example in my case, it is an singleton object. 2. The static library may be provided by an third party. And maybe the user also using an shared library provide by another third party, which has already linked the static library, for example boost.
You said:
By my understanding the global object will be exist in both *.so, and will cause issue because the function symbols in each shared library access different global variable.
That is correct. The global variable used by first .so will be different from the global variable used by the second .so.
As for your questions...
When link the executable, Why the GCC/LD doesn't report duplicate symbols error for this case?
As far as the executable is concerned, it only cares about the interfaces of the .so libraries. It doesn't care about the fact that they have been created by using the same static library(ies).
Does that means we never link to the same static library in an application's shared library and the executable itself?
It is OK if the static libraries don't have state. If they have state, you have to make a judgement call on whether the state needs to be global across the application or only in a shared library.
If the state needs to be global across the application, it will be better to create another shared library that provides access to the global state instead of putting it in a static library.
If the state needs to be maintained in each shared library, they putting it in the static library is OK. Even then, creating a shared library that provides access to the data will be a better solution.