Basic Example
suggest changeThe following example will contain a block of code that is meant to be split into several source files, as denoted by // filename comments.
Source Files
// my_function.h
/* Note how this header contains only a declaration of a function.
* Header files usually do not define implementations for declarations
* unless code must be further processed at compile time, as in templates.
*/
/* Also, header files usually include preprocessor guards so that a header
* is never included twice.
*
* The guard is implemented by checking if a preprocessor token unique to
* the header file is defined, and only including the header if it hasn't
* been included once before.
*/
#ifndef MY_FUNCTION_H
#define MY_FUNCTION_H
// A namespace-scope const variable has internal linkage, so each translation
// unit that includes this header gets its own global_value. my_function() is
// only declared here; the definition is in my_function.cpp.
const int global_value = 42;
int my_function();
#endif // MY_FUNCTION_H
// my_function.cpp
/* The corresponding source file includes the interface defined in the header
* so that the compiler knows what this file is implementing. Here it needs
* global_value, which is defined in my_function.h. Without that include, this
* source file would not compile.
*/
#include "my_function.h" // or #include "my_function.hpp"
int my_function()
{
return global_value; // return 42;
}
Header files are then included by other source files that want to use the functionality defined by the header interface, but don’t require knowledge of its implementation (thus, reducing code coupling). The following program makes use of the header my_function.h as defined above:
// main.cpp
#include <iostream> // A C++ Standard Library header.
#include "my_function.h" // A personal header
int main(int argc, char** argv)
{
std::cout << my_function() << std::endl;
return 0;
}
The Compilation Process
Since header files are often part of a compilation process workflow, a typical compilation process making use of the header/source file convention will usually do the following.
Assuming that the header file and source code file are already in the same directory, a programmer would execute the following commands:
g++ -c my_function.cpp # Compiles my_function.cpp to my_function.o
g++ main.cpp my_function.o # Links the object file that defines my_function()
# with main.cpp and produces the executable a.out
Alternatively, if one wishes to compile main.cpp to an object file first, and then link only object files together as the final step:
g++ -c my_function.cpp
g++ -c main.cpp
g++ main.o my_function.o