About the inclusion of headers (.h) and the proper compilation

2

Assuming I create a .h file for the specification of a function

func.h

#ifndef FUNC_H
#define FUNC_H

int xPy(int x, int y);

#endif //FUNC_H

Then I created the implementation of this function in a .c file, like:

func.c

int xPy(int x, int y) {
   int result;
   result = x+y;
   return result;
}

I can include "func.h" in a new file (suppose main.c )

Supposed code for main.c

#include "func.h"

int main() {
   int a = func(10, 10);
   return 0;
}

So far so good, though, in the build process seems not to be enough to do

gcc main.c -o main

I have to do

gcc func.c main.c -o main

I'd like to know why this is necessary. Should the #include "func.h" directive not have the compiler fetch the func.c file automatically?

In case I'm using GCC 8.2.0.

    
asked by anonymous 01.01.2019 / 21:01

1 answer

3

If you reread your question by carefully parsing the text, you will have the answer. It says that you want func.c to be included in your application. You say you already used #include "func.h" . Where are you including func.c ? At the compiler command line. Well, if not put somewhere, and this is the place, as the compiler will know what it is to put it. So the objective and direct answer to your question is that it needs to be put somewhere, there's no way the compiler can guess.

Next speculates about it making automatic. But what automation would this be? How to put func.h would make the compiler guess that it should put something else? What would this be? Are you thinking that because you put a file named func with extension .h you should also put another one with extension .c ?

This does not make sense, because these names, these extensions are mere conventions. In fact it would make little sense because a .c file may need more than .h or vice versa and .h refers to implementations that are in more than .c . What's more, .h is not required. And I'm not even talking about the extension that could be another, the header is not mandatory (although it may generate some future organizational difficulties, but it's just something you choose for your project).

One thing has nothing to do with another. Even inclusion is just a way to bring a text that is in another file to the current file, nothing more than that, the directive does not even process its contents, has no intelligence, is only part of a preprocessor, nor is it the compiler itself which is operating there.

You can read more at:

01.01.2019 / 21:39