Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a header file knows where the implementation of a function prototype is?

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?

like image 670
lmiguelvargasf Avatar asked Dec 25 '22 06:12

lmiguelvargasf


1 Answers

There are two different stages, compilation and linking.

  • During compilation, compiler only needs to know the prototype of the function.
  • During linking, the object files are actually linked together.

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.

like image 135
Sourav Ghosh Avatar answered Dec 28 '22 09:12

Sourav Ghosh