So if the source file with the call to the function is eventually linked to the actual function's source code, then why do you need to include headers across the rest of the source files if they are all linked to the function's source anyway? |
The compiler gets to a function call. It has a job to do. It must check that you are passing the correct parameter types to the function, and that you are dealing with the returned type appropriately. To do this, it must know what the correct input parameter types are, and what the correct return type is. If the declaration (or definition) isn't in this source file, how is the compiler supposed to know? The compiler gets to see one file only.
It can know this in one of two ways. Either is has already seen the function definition, or it has seen a function declaration. This is all a function declaration does; tells the compiler what the correct input and output types are.
The source code containing the call must be linked |
By the time linking happens, the source code no longer exists. All you have are a set of object code files, which the compiler promised make their function calls with the right number and types of input parameters, and handle the return type correctly. Each function call is joined to the right function in some other object file by the linker; the linker does this because the compiler effectively left a note in the object code, saying "here, please run the function with
this name, which takes
these inputs, and returns an object of
this type." Functions are identified by all these aspects in C++, so the linker needs to be given all these details, so the compiler needed to know all these details.
why do you need to include headers across the rest of the source files |
Not the rest. Only in any source file that uses one of the functions declared in the header.