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.
System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries. Your own header files contain declarations for interfaces between the source files of your program.
If you want your compiled code to be used from another compilation unit you will need the header files. There are some situations for which you do now need/want to have a headers. The first such case are main. c/cpp files.
The #include directive tells the C preprocessor to include the contents of the file specified in the input stream to the compiler and then continue with the rest of the original file. Header files typically contain variable and function declarations along with macro definitions. But, they are not limited to only those.
You're mixing two distinct issues here:
These are simply copied verbatim by the preprocessor into the place that include
s them. All the code of algorithm
is copied into the .cpp
file when you #include <algorithm>
.
Most modern linkers won't link in functions that aren't getting called in your application. I.e. write a function foo
and never call it - its code won't get into the executable. So if you #include <algorithm>
and only use sort
here's what happens:
algorithm
file into your source filesort
sort
(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 vector
of int
and a vector
of string
, the compiler will generate two copies of the whole code for the vector
class in your code. Since you are using it (otherwise the compiler wouldn't generate it), the linker also places it into the executable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With