I am really confused about this. I can't understand how code from library files is linked with a header file. Can anyone please help me?
-
https://www.learncpp.com/cpp-tutorial/header-files/ – Hack06 May 04 '20 at 20:04
-
2Short answer is that it isn't. There's nothing to stop you using a header without a library, or a library without a header. It's often convenient to distribute the two together, but it's only a convenience. – john May 04 '20 at 20:05
-
You can name lib files and their headers whatever you like. There's No language-enforced relation between them. They are just arbitrary names. – Jesper Juhl May 04 '20 at 20:14
-
1It might help if you illustrated your confusion with some examples. I think you're going to get lots of different answers because no-one is completely sure what you are confused about. – john May 04 '20 at 20:15
2 Answers
Forget about header files for a second, and look at the following program:
// Forward declare foo()
void foo();
int main() {
foo();
return 0;
}
I can compile this program fine, but if I try to link it, I'll get an error along the lines of:
I was promised that a function called
foo()
exists, but I can't find it anywhere.
Now, if I link the same program against a library that happens to provide the foo()
function then it'll be fine.
The header is just a formal way of packaging all the forward declarations of a library (and some other stuff) in a way that accurately documents the content of a library. But that's just a convention. As long as the forward declarations are visible to the compiler from somewhere, then that's all that is actually required.
Remember: #include "path/to/file.h"
literally means "copy paste the content of that file here."
So this is pretty much the same thing as my original program:
//foo.h
void foo();
//main.cpp
#include "foo.h"
int main() {
foo();
return 0;
}
The .lib files contain all the code of each function that was put in it. The header file contains the function declarations so that the compiler knows what the functions are.
If you have the following function in the library file:
int myFunction(char c, int a) {
//... Do something
}
The header file will contain the declaration: int myFunction(char c, int a)
The .lib file will contain the //... Do something part
The .lib is only use during compiling and serves no purpose at runtime because its contents (those that are used) will be put into the executable file.
For more information:

- 910
- 9
- 18