C++ header and implementation files: what to include?
There is a .h file and a .cpp file with the开发者_开发技巧 same name but different extension.
If I want to use what's in the .cpp file, do I include the .h file or the .cpp file?
The simple answer is that you almost always want to include .h files, and compile .cpp files. CPP files are (usually) the true code, and H files are (usually) forward-declarations.
The longer answer is that you may be able to include either, and it might work for you, but both will give slightly different results.
What "include" does is basically copy/paste the file in at that line. It doesn't matter what the extension is, it will include the contents of the file the same way.
But C++ code is, by convention, usually written this way:
SomeClass.cpp -
#include "SomeClass.h"
#include <iostream>
void SomeClass::SomeFunction()
{
std::cout << "Hello world\n";
}
SomeClass.h -
class SomeClass
{
public:
void SomeFunction();
};
If you include either of those, you can use the code from it. However, if you have multiple files that include the same .cpp file, you may get errors about re-definition. Header files (.h files) usually contain only forward declarations, and no implementations, so including them in multiple places won't give you errors about re-definition.
If you somehow manage to compile without errors when including .cpp files from other .cpp files, you can still end up with duplicate code. This happens if you include the same .cpp files in multiple other files. It's like you wrote the function twice. This will make your program bigger on disk, take longer to compile, and run a bit slower.
The main caveat is that this implementation/forward declaration convention doesn't hold true for code that uses templates. Template code will still be handed to you as .h files, but it (usually) is implemented directly in the .h file, and won't have accompanying .cpp files.
Usually it's better to write in the header file .h
#ifndef H_someClass
#define H_someClass
class SomeClass {
public:
void SomeFunction();
};
#endif
so that you won't get errors about re-definition when you need to include the .cpp file in other files.
The .h file usually contains the class declaration and the .cpp file the class definition (implementation). You should include the .h in the .cpp file.
A good rule of thumb is to NEVER include a .cpp file, because the #include
directive just copies the content of the included file into the including file. You may end with some multiple inclusion / definition and you definitely don't want to do that.
精彩评论