Question

When I compile a program which uses the STL using g++, how does the library get linked to my program? Dynamically or statically?

Statically sounds odd to me as that would mean every single C++ program which uses the STL would have to include it internally. On the other hand, dynamic linking sounds also odd to me as with all the OOP stuff I do not see how a library can be linked dynamically and also support different kinds of objects...

So what exactly is happening here?

Was it helpful?

Solution

The answer is in your question: STL stands for "Standard Template Library". As templates are in header files and are only instantiated when they are needed (e.g. used), you can include every single STL header (if you wanted), and if you did not use any of them, your binary would be no larger.

The STL is not a .lib or .a file that must be linked. It is a collection of header files.

OTHER TIPS

Templates are always instantiated as needed, and their instances tailored to the objects they use are part of the resulting binary.

The rest of STL not based on templates can be linked either statically or dynamically depending on your compiler settings.

Partially dynamically, partially statically :

  • statically get linked all template instantiations (explicit or implicit)
  • other things gets linked dynamically

This simple example :

#include <vector>

int main()
{
    std::vector<int> v;
}

compiled like

 g++  xxx.cpp -g  -Wall -Wextra

produce a file which links next libraries :

$ ldd a.out 
        linux-vdso.so.1 =>  (0x00007fffa7767000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f353bee7000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f353bcd1000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f353b908000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f353b604000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f353c20c000)

and it has vector symbols :

$ nm a.out | grep vector
000000000040073e W _ZNSt6vectorIiSaIiEEC1Ev
000000000040073e W _ZNSt6vectorIiSaIiEEC2Ev
0000000000400758 W _ZNSt6vectorIiSaIiEED1Ev
0000000000400758 W _ZNSt6vectorIiSaIiEED2Ev
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top