Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include .cpp instead of header(.h)

Tags:

There are some cases when we include .cpp file instead of standard header file (.h), for example:

#include "example.cpp" 

instead of

#include "example.h" 

It seems to work but is this safe or should I avoid it?

What about the compilation time?

like image 892
sysop Avatar asked Feb 12 '12 23:02

sysop


People also ask

Can I include cpp file without header?

You should never include a cpp file ( or anything that is not a header ). If you want to compile a file, pass it to the compiler. If you both #include and compile a source file, you'll get multiple definition errors.

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.

Should I include in header or cpp?

In general, you should only include headers in . h files that are needed by those headers. In other words, if types are used in a header and declared elsewhere, those headers should be included. Otherwise, always include headers only in .


2 Answers

It's lazy coding. Use header files. Yes they can increase compile time but they mean that you can easily re-implement chunks of your code, or better yet, another developer could at anytime. The header file serves as a template for what your C/C++ code is going to do. It's a bad idea to discard or ignore it.

like image 99
zellio Avatar answered Oct 19 '22 22:10

zellio


I agree with Kerrek SB.

I did this once. I was building an excellent, widely used compression library that needed to be built separately for 8-bit images and for 12-bit images. The cleanest way I could come up with to fit this into the build system was (oversimplifying a bit) to have two master .cpp files, one that set #defines for an 8-bit build, the other for a 12-bit build. The master .cpp files then #included the source files of the compression library.

It's okay to not follow a general rule if you understand the rule well enough to know the reasons for it and why it might not apply in your case. (But those cases ought to be rare.)

like image 26
Dan K Avatar answered Oct 19 '22 22:10

Dan K