C ++ when to include cpp even if we have a .h file

I am reading the book Absolute C ++ 5th edition. On page 716, I really don't understand why this is needed: "pfarray.cpp"

Including "pfarray.h" is not enough?

More specifically, even if we have declarations in the .h file but implementations in the .cpp files, when else do we need to include the .cpp file?

Thanks in advance.

+3


source to share


2 answers


When you write #include anything.any_extension

, the extension doesn't really matter to the preprocessor. It's really like "take the content from this file and insert it into this file", sort of a crude mechanism. This way, you can include everything without errors, provided that the code inside is legal and you can name the header file with any extension. So you can even name them with an extension .txt

, and it doesn't really matter to the preprocessor.

I would suggest that the practice of including source files is rather confusing, mainly from a build point of view, as it is not very clear if the source file (cpp, cc, etc.) should be created as a separate object file to link against or # included or both.



But sometimes it is done. For example, it pfarray.cpp

can contain an implementation for a template, since templates usually need their full implementation visible at compile time on the site generating the code, and sometimes authors establish the habit of #include files with source file extensions to avoid embedding the implementation of the part in one and the same header file, while still consistent with the style, which facilitates putting all such details in files named according to the source file convention.

Another reason it can be done, but I don't think the reason it was done in your case is because of build optimizations (see Unity build). It is sometimes more efficient to compile and link fewer files, so using #include

for source files can be a crude way to bundle them all together into a single build target.

+5


source


You don't have to.

A translation unit is a group of definition and declaration files. Compiling a translation unit, the compiler needs to know everything about the declarations and re-parse them over and over again. Definitions, on the other hand, can only be compiled once and reused for other units.



The translation unit can be split in files .h

and .cpp

. You must place declarations in .h

and definitions in files .cpp

to obey the same definition rule. This approach also reduces compilation time.

Writing templates-d classes and functions (no specialization), some coders (bad habit in my opinion) put implementations in files .cpp

and they have to include them at the end of the corresponding .h

file or in the file .cpp

they need. It's just confusing. The best naming convention is to rename these file types .cpp

to .impl.cpp

and include them at the end of your file .h

.

+5


source







All Articles