Why is Linking necessary?

I am fairly new to C++, and I've just started to learn my first libraries outside of the STL lib. Just recently I learned about the C++ assembly line for making an executable.
So I understand that in pre processing all the # are translated into valid C++ code. And from my understanding #include copies and pastes code from another source file to this source file. But if you do this then why do you need to link the libraries again? Shouldn't the .o file from compiling already contain everything that you need?
Last edited on
> And from my understanding #include copies and pastes code from another source file to this source file.
This is where you're wrong (or not entirely right(*))

A function like this from cstdio would be in the header file as
extern fgets ( char * str, int num, FILE * stream );

Your compiler writer put the code for this into a library.
1
2
3
char *fgets ( char * str, int num, FILE * stream ) {
    // do something
}


The compiler normally links the standard libraries for you, but when you start using 3rd party code, then libraries become pretty standard fare as something you have to cope with.

You can always open a .h file in your code editor.
If you see lots of functions ending with ;, then you'll need the associated library.
If you see lots of templates and inline functions, then you might only need to include the header.


(*) Some C++ header files which are heavily templated have all the code in the header files, and the template expansion creates the version of the code appropriate for you.
Eg, when you say std::vector<int> foo;

the .o files point to meerly a "HEY I DON'T KNOW WHAT THIS FUNCTION IS LOCATED SO TELL ME LATER", then the linker replaces those with the real address.
Topic archived. No new replies allowed.