Including .h and .cpp Files: Understanding the Differences
In C development, incorporating other files into the source code is crucial. However, the inclusion of header (.h) files and implementation (.cpp) files requires some understanding.
Consider the following code:
main.cpp #include <iostream> #include "foop.h" // Including the header file int main() { int x = 42; std::cout << x << std::endl; std::cout << foo(x) << std::endl; return 0; }
foop.h #ifndef FOOP_H #define FOOP_H int foo(int a); // Declaring the function prototype #endif
foop.cpp #include "foop.h" // Including the header file, just for safety int foo(int a) { return ++a; }
This code successfully compiles because we have included the header file ("foop.h") in both main.cpp and foop.cpp.
Why not include .cpp files?
Now, let's see what happens if we replace the "#include "foop.h"" line in main.cpp with "#include "foop.cpp":
main.cpp #include <iostream> #include "foop.cpp" // Including the implementation file
This will result in a compiler error. Why? Because including an implementation file will duplicate the code it contains into the current source file. In our example, the function "foo" would be defined twice: once in main.cpp and once in foop.cpp. This duplication confuses the compiler, leading to the "multiple definition" error.
Conclusion
Therefore, it is crucial to include header files (.h) in both the primary source file and any additional source files that use the declared functions. Implementation files (.cpp) should be included in only one source file to avoid duplicating code definitions.
The above is the detailed content of Why Can\'t I Include .cpp Files Like I Include .h Files in C ?. For more information, please follow other related articles on the PHP Chinese website!