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 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

but how does the compiler know where the actual functions are if the header file does not tell it?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.