My understanding is that when linking, if symbols are declared with 'extern' keyword, then the compiler will not complain the absence of its definition. Furthermore linker either will not have any problem since it will create the symbol table at first and later will detect the proper source code and will fill its defintion.
It seems that there are no problems at all when building a program composed of multiple files without header files - if all the symbols absent in one file are well declared with 'extern'.
If recognitions of symbols of other files can be detected with 'extern' keyword, then why should there be the 'header' files?
My understanding is that when linking, if symbols are declared with 'extern' keyword, then the compiler will not complain the absence of its definition.
The extern
keyword in C tells the compiler that the declaration it is in describes identifiers but does not define them.1 This is a compile-time effect, not something that happens when linking.
If recognitions of symbols of other files can be detected with 'extern' keyword, then why should there be the 'header' files?
Putting declarations in a header files allows us to include them in multiple source files without retyping them or copying and pasting them. That avoids typing errors and helps ensure the same declaration is used for an identifier throughout a program. Further, it is good practice to include the header file that declares identifiers in the source file that defines them, so that the compiler sees both the declaration and the definition in the same compilation and will warn if they are inconsistent.
Another reason is that the header file is considered to be something published by the author of the related source file(s) to tell other programmers what the source files provide. Before a programmer could write their own declarations with extern
in their own source files, somebody would have to tell them what those declarations are. The person who writes source file NiftyLibrary.c could (and should) write a manual listing all the declarations of the functions (and what those functions do), and then anybody using NiftyLibrary.c could read the manual and type the necessary declarations into their program. But it is easier if the library author provides NiftyLibrary.h and other programmers merely include the header instead of retyping everything.
1 This is one of the functions of extern
. The full semantics are complicated due to the history of C development.