Including .cpp Files: A Case of Function Duplication
When developing in C , it is generally recommended to include header (.h) files for functionality, rather than implementation (.cpp) files. Including .cpp files can lead to errors due to function duplication.
Let's consider the following code example:
// main.cpp #include <iostream> #include "foop.h" // Header file containing the function declaration int main() { std::cout << foo(42) << std::endl; return 0; } // foop.h int foo(int a); // Function declaration // foop.cpp int foo(int a) { // Function definition return ++a; }
This code will compile and run correctly because the header file (.h) only includes the declaration of the foo() function, while the definition is provided in the separate .cpp file.
However, if we replace the header file inclusion in main.cpp with the .cpp file inclusion:
// main.cpp #include <iostream> #include "foop.cpp" // Implementation file containing the function definition
This will result in a compiler error:
multiple definition of foo(int) first defined here
This is because the preprocessor copies the contents of the included file into the main source file. Including the .cpp file effectively copies the foo() function definition into main.cpp, which results in a duplicate definition of the function.
To avoid function duplication, it is recommended to include header (.h) files only for declarations and .cpp files for definitions. This helps ensure that functions are defined only once in the program.
The above is the detailed content of Why Should I Include Header (.h) Files Instead of Implementation (.cpp) Files in C ?. For more information, please follow other related articles on the PHP Chinese website!