Difference between revisions of "Cpp Coding Standards/HEADERS"

From Apache OpenOffice Wiki
Jump to: navigation, search
(some improvements)
(No difference)

Revision as of 16:20, 22 May 2007

Topic-Id: HEADERS

What to do or do not with header files.


Summary

Self Sufficient and Minimal (Self)

When included a header file should be self sufficient and minimal.

  • Include definitions for superclasses, data members, typedefs, macros, types denoted in exception-specifications, ...
  • Create forward declarations for everything else (but note that this introduces unwanted coupling, when for example a template declaration is later on extended with defaulted parameters, or a struct definition is replaced with a typedef)
  • Include the definition as late as possible, this helps reduce physical dependencies
// Foo.hxx
// Superclass and data member
#include "Super.hxx"
#include "Data.hxx"

// Forward declarations
class Param;

// This does not need a class definition
Param doSomething1(Param aParam);

class Foo : public Super
{
 public:
  // This does not need a class definition either
  Param doSomething(Param aParam);
 
 private:
  Data mData;
};
// Anotherfile.cxx
#include "Foo.hxx"
#include "Param.hxx" // Now we need the definition

...
 Param p;
 p = doSomething1(p); // Error without the definition


Include Directly (IncDirect)

Include the header files for all types you need directly, not via another file.

Precompiled headers (IncPCH)

  • The first statement in each cxx files should be the inclusion of precompiled headers. There must be no other includes, no definitions and no include guards around the include statement. Forget this for a new file and you break the build.
  • Assume the precompiled header file is empty and include all your headers normally.
#include "precompiled_foo.hxx" // May or may not contain includes for Foo.hxx and Bar.hxx

#include "Foo.hxx"
#include "Bar.hxx"

Internal Include Guards (IncGuards)

Internal include guards are good but don't use the external ones. They add a lot of noise for a non-existent benefit.

// Foo.hxx

// Yes, use internal include guards
#ifndef INCLUDED_FOO_HXX
#define INCLUDED_FOO_HXX

// No include guards here
#include "Superclass.hxx" 
...

#endif
// Bar.cxx

// No include guards here
#include "Bar.hxx"
#include "Foo.hxx"
#include "Baz.hxx"

Personal tools