C ++ header and implementation files: what to include?

There is a .h file and a .cpp file with the same name but with a different extension.

If I want to use what is in the .cpp file, should I include the .h file or the .cpp file?

+4
source share
3 answers

The simple answer is: you almost always want to include .h files and compile .cpp files. CPP files (usually) are the true code, and H files (usually) are forward-declarations.

The longer answer is that you can enable it and it may work for you, but both will produce slightly different results.

What is include, is basically copy / paste the file to this line. No matter what the extension is, it will contain the contents of the file in the same way.

But C ++ code is usually written as follows:

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 any of them, you can use the code from it. However, if you have multiple files containing the same .cpp file, you may get errors regarding overriding. Header files (.h files) usually contain only declarations in the forward direction and do not have implementations, so including them in several places will not give you errors with regard to overriding.

If you can somehow compile without errors when including .cpp files from other .cpp files, you can still get duplicate code. This happens if you include the same .cpp files in several other files. It is like you wrote this function twice. This will make your program larger on disk, take longer to compile, and run a little slower.

The main caveat is that this implementation / transition declaration declaration is not valid for code that uses templates. The template code will still be passed to you as .h files, but it (usually) is implemented directly in the .h file and will not accompany .cpp files.

+23
source

An .h file usually contains a class declaration and a .cpp file class definition (implementation). You must include the .h in the .cpp file.

A good rule is to NEVER include a .cpp file, because the #include directive simply copies the contents of the included file to the included file. You can complete several multiple inclusions / definitions, and you definitely don't want to.

+3
source

This is usually best written in the .h header file.

 #ifndef H_someClass #define H_someClass class SomeClass { public: void SomeFunction(); }; #endif 

so you won’t get errors when overriding when you need to include the .cpp file in other files.

+3
source

Source: https://habr.com/ru/post/1310594/


All Articles