dsyleixa123 wrote: ↑
Sat Sep 26, 2020 4:38 pm
to link it automatically, without extra command line parameters?
or why is it needed here?
or is the .h file included because of the same line #include "mylib.h" in my mainprogram.c ?
Imagine you have a C file with your main() in it. Call it "main.c".
You also have another file with a bunch of functions in it that you want to call from main.c. Let's call that "funcs.c"
Now, when you compile main.c it fails. Because it knows nothing about any of those functions out there somewhere that it wants to call.
So we introduce a header file, call it "funcs.h". In there we put declarations for all the functions in funcs.c.
And we add '#include "funcs.h"' to the top of main.c.
Now we can compile main.c into an object file because it knows all about the functions it want to call. Their names, their parameters and parameter types, their return values and types. Note that at this stage it does not mater where funcs.c is. Or even it if it exists at all!
With all the above we can now compile main.c in to an object file main.o. But we don't have a complete executable yet. We need to compile funcs.c as well and link the resulting object files, main.o and func.o into an executable program.
How does the compiler know where funcs.h is when it compiles main.c? Well, it will look in the current directory. It will also look in any directory specified on the command line with the -I option: https://www.rapidtables.com/code/linux/gcc/gcc-i.html
In short. A program is built by compiling a bunch of .c source files into a bunch of .o object files.
They can all be compiled totally independently because the various .h header files tell them about what is out there that they are using.
Then the complete executable is built by linking all those .o object files together.
Header files do not magically tell the compiler where the actual C source files that implement any particular header files declarations are.
Memory in C++ is a leaky abstraction .