4 ms·
There is no magic in .h files, you can think them as plaintext. The actual magic happens in .c files. Since C requires objects to be declared before using them,
by gnulinux 6y ago
There is no magic in .h files, you can think them as plaintext. The actual magic happens in .c files. Since C requires objects to be declared before using them, you need to declare objects used in multiple units together. Let's say you have a function `int f(int)`. You want to use this function both in apple.c and pear.c. How would you do it. Well you need to write a f.h such as
int f(int);
then in apple.c
#include "f.h"
int apple() {
int x = f(10);
// rest of the code
}
You can think this as a copy paste of f.h such that, apple.c is equivalent to:
int f(int);
int apple() {
int x = f(10);
// rest of the code
}
but what "is" f. To "define" f you need another .cpp file that implements f, let's call it f.c:
#include "f.h"
int f(int x) {
return x*x;
}
now you compile f.c, apple.c, pear.c. These will create f.o, apple.o and pear.o object files. Then you link these together to create your application. e.g. if f.h is in include/ dir:
gcc -c apple.c -I include/ -o apple.o
gcc main.c -I include/ apple.o pear.o f.o -o main
Here, assume that main.c defines int main().