When I include some function from a header file in a C++ program, does the entire header file code get copied to the final executable or only the machine code for the specific function is generated. For example, if I call std::sort from the <algorithm> header in C++, is the machine code generated only for the sort() function or for the entire <algorithm> header file.
I think that a similar question exists somewhere on Stack Overflow, but I have tried my best to find it (I glanced over it once, but lost the link). If you can point me to that, it would be wonderful.
You’re mixing two distinct issues here:
Header files
These are simply copied verbatim by the preprocessor into the place that
includes them. All the code ofalgorithmis copied into the.cppfile when you#include <algorithm>.Selective linking
Most modern linkers won’t link in functions that aren’t getting called in your application. I.e. write a function
fooand never call it – its code won’t get into the executable. So if you#include <algorithm>and only usesorthere’s what happens:algorithmfile into your source filesortsort(and functions it calls, if any) to the executable. The other algorithms’ code isn’t getting addedThat said, C++ templates complicate the matter a bit further. It’s a complex issue to explain here, but in a nutshell – templates get expanded by the compiler for all the types that you’re actually using. So if have a
vectorofintand avectorofstring, the compiler will generate two copies of the whole code for thevectorclass in your code. Since you are using it (otherwise the compiler wouldn’t generate it), the linker also places it into the executable.