1

How does the compiler know which source file is the one I am including? Does it work as long as the name of the header and source file are the same? For example, the header file example.h refers to example.c and so including example.h would be already enough?

1 Answers1

0

How does the compiler know which source file is the one I am including?

It doesn’t. The compiler only knows what you tell it. Header files are designed to tell the compiler what exists elsewhere.

Does it work as long as the name of the header and source file are the same?

It makes no difference. By convention, we humans find it easier to name them the same so that we can correlate example.h and example.c as the header and source for the same module.

For example, the header file example.h refers to example.c and so including example.h would be already enough?

It should be enough to tell the compiler what things exist in example.c.

Remember, the header’s purpose is to explain what exists in other source file(s). (And to declare types, which by themselves don’t create code.)

This is a C question, but there is a very good overview at learncpp.com that applies equally to C as it does to C++. Specifically, you may wish to read through:

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39
  • but how does the compiler know where the actual functions are if the header file does not tell it? – Captain Toad Jan 18 '22 at 05:36
  • Connecting everything together is the job of the _linker_. Another really good explanation for how compilation and linking work is [David Drysdale’s _Beginner’s Guide to Linkers_](https://www.lurklurk.org/linkers/linkers.html). – Dúthomhas Jan 18 '22 at 06:04