EnhancedElegance
EnhancedElegance

Reputation: 33

Compiling a library that uses another library in C++

I don't quite understand how the compilation of a library that uses another library work. From what I understand the is 4 cases :

1) Compiling a static library (A) that uses a static library (B) : The compilation would work, but linking against library A would not work because a static library is just an archive containing the .o files resulting from the compilation of A, and not from B. Is it true that when creating a static library, the compilation phase searches for function definition and find them in the header. At the linking phase, the compiler searches for function implementations in the library B and the compilation is successful if it finds them but it doesn't actually put the function implementations in the static library A. And that's why when linking against A it doesn't work

2) Compiling a static library that uses a dynamic library : I think both the creation of A and the use of A would work, but why is that? What does the compiler actually put in the dlls/so?

3) Compiling a dynamic library that uses a static library : Would this work?

4) Compiling a dynamic library that uses another dynamic library : Would this work too?

Thanks for your time.

Upvotes: 0

Views: 4840

Answers (1)

Codo
Codo

Reputation: 78795

If you create a library or program in C or C++, the build process consists of two steps:

  1. Compiling each C/C++ file into an object file

  2. Linking the object files and creating library or executable (If you create a static library, it isn't really linking; but let's use this word for simplicity.)

Compliation

If you compile code that makes use of a library, you need header files (.h) for the library. They declare the public functions and classes in the library. You don't need to binary files for compilation.

Linking

For the linking step, you then need the binary file of the static or dynamic library (.lib or .a for static libraries, .dll or .so for dynamic libraries).

Dependencies between libraries

If you create a static library, all your object files will be put into a new library file. Nothing from the consumed library (static or dynamic) will be included. But it will be needed when somebody uses your library. So your library isn't self contained.

If you create a dynamic library and consume a static library, the necessary code from the static library will be included into your dynamic library. The new dynamic library will be self contained as far as the consumed library is concerned.

If you create a dynamic library and consume a dynamic library, only a reference to the consumed library will be included. So to run the final product, both the new and the consumed library will need to be available.

Upvotes: 13

Related Questions