Home >Backend Development >C++ >Why does including a .cpp file instead of a .h file in C lead to errors?
Including Header Files versus Source Code
When working with multiple source files in a C program, it's crucial to understand the distinction between including header files (.h) and source code files (.cpp).
In the example provided, you encountered an error when including "foop.cpp" instead of "foop.h" in the main.cpp file. This is because header files are specifically designed to declare function prototypes and other necessary information, while source code files contain the actual function implementations.
Including Header Files
Including header files allows the compiler to locate and recognize functions defined in other source code files without duplicating the definitions. By including "foop.h," the main.cpp file gains access to the foo() function prototype, enabling the program to call it without knowing the full implementation details.
Including Source Code Files
In contrast, including "foop.cpp" directly would copy all the code from that file into the main.cpp file, leading to a multiple definition error. Since foo() is defined both in foop.cpp and main.cpp, the compiler becomes confused about which definition to use.
How It Works
When you include a header file, its contents are effectively copied into the current source code file. For instance, including "foop.h" would result in the following equivalent code in main.cpp:
// Header file contents int foo(int a); int main(int argc, char *argv[]) { // Rest of the main.cpp code }
However, including "foop.cpp" would lead to this:
// Source code file contents int foo(int a){ return ++a; } int main(int argc, char *argv[]) { // Rest of the main.cpp code }
Consequences
Including source code files directly can have unintended consequences, such as:
Best Practice
Therefore, it's always good practice to include header files (.h) when referring to functions and declarations, and to keep source code implementation in separate files (.cpp). This ensures code modularity, avoids errors, and improves code readability.
The above is the detailed content of Why does including a .cpp file instead of a .h file in C lead to errors?. For more information, please follow other related articles on the PHP Chinese website!