views:

758

answers:

3

Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible?

Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case?

I am using Microsoft Visual Studio 2003.

+4  A: 

The linker will not automatically bring in the other libraries, but you can use #pragma comment (lib, "static.lib") to simplify the process of linking the additional files by adding the pragma to your header files.

Stephen Nutt
A: 

Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible?

Yes for instance when you call windows functions from within your static lib they are normally from some dynamic library so there should be no difference.

Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case?

Having dependencies like this one could cause problems later, I would suggest that you instead dynamically load the libraries using LoadLibrary(), that way you don't need to keep track of such dependencies while compiling/linking.

Anders K.
I agree that you should be careful with library dependencies, but I think LoadLibrary is overkill in this case. I have only required it for plugin type architectures.
iain
+8  A: 

Static libraries are not linked. They are just a collection of object files (*.obj or *.o) that are archived together into a library file (kind of like a tar/zip file) to make it easier for the linker to find the symbols it needs.

A static lib can call functions that are not defined (but are only declared in a header file), as it is only compiled. Then when you link an exe or dll that uses the static lib you will have to link with another library that provides the called from the static lib but not defined in it.

If you want to the linker to automatically link other libraries Stephen's suggestion will work and is used by very reputable libraries like boost and stlport. To do this put the pragma in the main header file for the static library. You should include the static library and its dependants.

However IMO this feature is really meant for library writers, where the library is in the system library path so the linker will easily find it. Also in the case of boost and stlport they use this feature to support multiple version of the same libraries with options defined with #defines where different options require different versions of the library to be linked. This means that users are less likely to configure boost one way and link with a library configured another.

My preference for application code is to explicitly link the required parts.

iain