I'm new to C family programming and compiling. I'm trying to understand what .c/.cpp files vs .h files are on a low technical level. I understand .h files are used to specify an interface and .c or .cpp files for implementation. However I'm wondering if this difference is reflected in how the compiler works or if it is "just" a naming convention to simplify for us humans? Could you in theory have the implemntation in a .h file and still have it compile? Or specify an interface in a .c file? I'm asking to better understand what the compiler actually does.
Only source files are passed to the compiler (to preprocess and compile it). Header files aren't passed to the compiler. Instead, they are included from source files.
Header files are inserted into source files which include them, by the preprocessor. So at compilation, there are no header files. There are only preprocessed source files which contain the contents of all the included header files. So in that sense, header files are compiled.
A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
h files are header files that are prewritten for our compiler. *. c files are our C source code files in which our code is written and are created by the user. Actually users can also create his/her own header files by writing the code in a text file and saving it with an extension .
Technically, there is no difference between any extension as far as the compiler is concerned. It's same as if you had typed manually the contents of any file in place where you put the #include
. You can type #include "foo.pdf"
and the compiler will include a file foo.pdf successfully, as long as that file contains code (despite the extension)
By convention now, one usually puts declarations in .h/hpp files (or template definitions) and the implementation in .c/cpp files.
Many libraries have a single-file implementation, with the aid of inline variables/functions as well.
Sometimes also the include file does not even exist, for example when including a standard STL file (like string
), the compiler might not read the file at all, but cache it/implement it however it wants.
More info on #include
in MSDN and CPPReference.
The compiler does what you tell it to do. It will compile files which you specify as its inputs, and as part of this compilation, it will include other files in these input files if you tell it to do so using #include
preprocessor directives.
If you tell the compiler to compile a .h
file (and pass in command-line options to make it treat it as a source file, such as -x c
for gcc), it will compile it just fine. If you #include "a.cpp"
, it will get included normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With