Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
neuromancer Avatar asked May 22 '10 08:05

neuromancer


2 Answers

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.

like image 91
Merlyn Morgan-Graham Avatar answered Nov 15 '22 00:11

Merlyn Morgan-Graham


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.

like image 35
Raghad Avatar answered Nov 14 '22 23:11

Raghad