Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ include header conventions

Suppose I have a file X.h which defines a class X, whose methods are implemented in X.cc. The file X.h includes a file Y.h because it needs Y to define class X. In X.cc, we can refer to Y because X.h has already included Y.h. Should I still include Y.h in X.cc ?

I understand that I don't need to and I can depend on header guards to prevent multiple inclusions. But on the one hand, including Y.h makes X.cc a little more independent of X.h (can't be completely independent of course). What is the accepted practice?

Another example: including <iostream> in both .h and .cc files. I see some people do this and some don't.

like image 268
user231536 Avatar asked Mar 31 '10 17:03

user231536


People also ask

Can you use include in a header file?

You make the declarations in a header file, then use the #include directive in every .cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the .cpp file prior to compilation.

What should be included in header file in C?

The header file contains only declarations, and is included by the . c file for the module. Put only structure type declarations, function prototypes, and global variable extern declarations, in the . h file; put the function definitions and global variable definitions and initializations in the .

Should includes be in header or C?

c') should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.

What is #include in C?

The #include directive tells the C preprocessor to include the contents of the file specified in the input stream to the compiler and then continue with the rest of the original file.


1 Answers

Be minimal. In headers, prefer forward declarations to full definitions. Use iosfwd instead of ostream, for example.

That said, X.h and X.cc represent the same logical unit. If your dependency on Y.h ever changed (for example, turned it into a forward declaration), you'd be changing the class anyway. So you can move #include "Y.h" to X.cc justifiably.

In other words, X.cc and X.h go hand in hand. X.cc can reliably assume what's in X.h. So there's no need to re-include something if X.h does.

Dependencies where you 'include it anyway' occur with resources other than your own. For example, if you needed Z.h, you'd include it even if Y.h does. X.h does not get to reliably assume the contents of Y.h because X.h doesn't go with Y.h, it uses it.

like image 144
GManNickG Avatar answered Sep 28 '22 23:09

GManNickG