C++ Why does this specific situation cause a symbo

2019-08-09 22:19发布

问题:

I'm working on an application where there's a 'core' and multiple plugins. I'm using Qt on Linux, and I use Qt's plugin loader system. Plugins are created as shared object files (*.so) and loaded dynamically. If I link to a library with a plugin, and that library links to additional libraries, I often get an 'undefined symbol' error from the application. To get around it, I need to link the plugin to the additional libraries as well...

Plugin links to LibA

LibA links to LibB, LibC

LibA is compiled as static. When I try to load the plugin, I'll get an undefined symbol error, like so:

unable to load shared library 'myPluginName.so':
myPluginName.so: undefined symbol: _ZN3BlahBlahD2Ev

To fix this I can use filt to unmangle the symbol name, figure out which lib the symbol belongs in (say LibB), and then compile like:

Plugin links to LibA, LibB

LibA links to LibB, LibC

I don't know why the error occurs. If LibA links to LibB and LibC, why should Plugin have to 'know' about LibB as well? Why doesn't this error occur in all cases (ie no errors related to undefined symbols with LibC)?

I'd appreciate any input.

-kf

回答1:

You have to keep in mind that a static library is nothing more than a collection of object files packaged together into a single file. If your plugin needs LibA, and LibA needs LibB and LibC, then when you link your plugin you have to tell the linker where LibA, LibB and LibC are.

If you work with dynamic libraries it would be a different story. A .so is already linked, so all its references were already resolved. If LibA was a dynamically linked library then your plugin would only need to link against LibA.so, since a link step already occurred to bind LibA to its own dependencies.



回答2:

If static libraries were to include symbols from their static dependencies, you would get all sort of nasty warnings and errors due to multiply defined symbols.

Consider the case:

  • libA depend on libB and libC
  • => libB depend on libD
  • => libC depend on libD

At least that's my experience from the MSVS world.



标签: c++ qt linker