I have the following files:
main.c
#include <stdio.h>
#include "my_math.h"
int main()
{
int a = 10, b = 5;
add(a, b);
return 0;
}
my_math.h
int add(int a, int b);
my_math.c
#include "my_math.h"
int add(int a, int b)
{
return a + b;
}
I know that using #include "my_math.h"
copies the content of my_math.h file within the file where it is called. However, how does main.c file where the implementation of add() function is?
At the beginning I thought that my_math.h and my_math.c should match the name, but not the extension, but I have changed the name from my_math.c to my_matho.c and everything is working as previously, so how the heck C know where the implementation of the function is?
I am using the following command to compile:
gcc -g -O0 -Wall main.c my_math.c -o main
One more question is it the same the previous command than:
gcc -g -O0 -Wall my_math.c main.c -o main
so it means that the order in which I indicate the files to be compiled does not matter?
There are two different stages, compilation and linking.
So, during compilation, the where part is not required. However, while linking, the function should be present in one of the object files which are being linked together.
To elaborate, that is why we see that, even with a missing header file (forward declaration of a function) but with all required object files, the compilation and linking can happen (with warnings, obviously) (and linker can actually find and link the required function implementation), but even if with the proper header file, if you don't supply the required object file which contains the actual definition, the linker will scream at you throw error.
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