2
votes

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?

3
Templates are always instantiated as needed (therefore they are always included in your binary) The rest of it can be linked dynamicallyErbureth
STL has become part of C++, hence, it is linked as C++ (dynamically if needed)user2249683
@DieterLücking: The C/C++ runtimes can be linked statically or dynamically, but the STL portion is nothing but a collection of header files.Zac Howland
STL is anything but object-oriented.n. 1.8e9-where's-my-share m.
@ZacHowland I bet some template specializations are extern and come with the library (eg: locale)user2249683

3 Answers

6
votes

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.

0
votes

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.

0
votes

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