Tutorial :Is there a standard #include convention for C++?



Question:

This is a rather basic question, but it's one that's bugged me for awhile.

My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.

I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.

Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?

For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.


Solution:1

I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.

Bar.h:

class Foo;    class Bar  {      Foo * m_foo;  };  

Bar.cpp:

#include "Foo.h"  #include "Bar.h"  


Solution:2

Some best practices:

  • Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers
  • Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers
  • Every header is wrapped with:

    #ifndef HEADER_XXX_INCLUDED  #define HEADER_XXX_INCLUDED  ...  
    
    
    
    
    
            
Previous
Next Post »