+ 2

What is the difference between header file and source file in C++

is there functional purpose for writing in the header or source file

14th Dec 2016, 3:03 PM
Kukoyi Michael Oluwatomisin
Kukoyi Michael Oluwatomisin - avatar
1 Odpowiedź
0
Header files are typically used for declaration purposes, while source files are used for implementation (definition) purposes. This allows a source (say b.cpp) file to include your header file (say a.h) to call the functions in a.cpp without requiring access to a.cpp. When b.cpp is compiled the a.h is used to inform the compiler that those function bodies will be in a different compilation unit (a.obj in Windows). So the compilation will succeed even though the compiler cannot resolve those function calls. The linker then resolves these unresolved calls between the different compilation units and creates the final executable. This process is called 'separate compilation' (i.e. all CPP files are separately compiled) and is a fundamental principle on which all CPP compilers rely. This also allow you to build libraries (DLLs or LIBs) and only need to distribute the header files with your DLL/LIB to use your library. You do not need to provide the CPP sources. Templates are used differently in this regard. Because templates are instantiated at the call point, the compiler needs access to the template class/function body at that point. So 'separate compilation' does not work in this case. It is therefore normal for template bodies to be defined in header files.
15th Dec 2016, 9:36 AM
Ettienne Gilbert
Ettienne Gilbert - avatar