Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of a .cpp file containing only a single #include?

I am starting some work using a third party library and when building it in Visual Studio 2010, I noticed I was receiving this linker warning many times (LNK4221). I looked at the sources used in creating the object files that were being linked and found that all of the implementation for these is located in the header files. Interestingly, I also noticed the project included corresponding .cpp files containing only a #include for the header with the implementation.

I am curious - what is the point of this and why would I want to use this technique? If the .cpp files aren't adding any value to the project, why shouldn't I just remove them to get rid of the linker warnings?

I tried searching for similar questions, but didn't find anything of interest. If you know of any, please link them.

like image 894
Joe Bane Avatar asked Jul 18 '12 15:07

Joe Bane


People also ask

What does .cpp file mean?

Files with CPP file extension are source code files for applications written in C++ programming language. A single C++ project may contain more than one CPP files as application source code.

Why don't we include .cpp files?

If you #include a cpp file in several other files in your program, the compiler will try to compile the cpp file multiple times, and will generate an error as there will be multiple implementations of the same methods.

Does every .h file need a .cpp file?

Cpp files don't always have to have a header file associated with it but it usually does as the header file acts like a bridge between cpp files so each cpp file can use code from another cpp file. One thing that should be strongly enforced is the no use of code within a header file!

What is the difference between a .cpp and .h file?

. h files, or header files, are used to list the publicly accessible instance variables and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.


2 Answers

Was the single #included file stdafx.h? I. That case, you're dealing with precompiled headers. The normal setup is for one .cpp file having "generate precompiled headers" compiler option, and the rest of the .cpp files in your project having "use pch".

like image 144
snemarch Avatar answered Sep 18 '22 08:09

snemarch


I'm using this to make sure, that the header is at least in one file included at the first position. By doing so, I make sure that the header is compilable on it's own.

To convence the linker to not issue a warning, one could use an external variable with a very large variable:

int variable_with_a_name_that_includes_the_file_name_somehow = 42;
like image 42
Torsten Robitzki Avatar answered Sep 22 '22 08:09

Torsten Robitzki