Best practices for use of C++ header files

Navaneeth K N picture Navaneeth K N · Jan 4, 2009 · Viewed 18.2k times · Source

I have the following doubts on header files usage.

1 - Include guards placing after comments

/* Copyright Note and licence information (multiple lines) */
#ifndef FOO_H
#define FOO_H
// Header file contents
#endif

Herb Sutter says in his "C++ coding standards" book that code like the above is problematic. He is saying the "#ifndef" statements should appear in the first line of the header file. I haven't felt this as convincing. Is this followed by you guys/gals in header files?

2 - Using namespaces in header files

#ifndef FOO_H
#define FOO_H
namespace FooNameSpace{
    // Header file contents
}
#endif

Is the above code using correct practice? I mean, do you use namespaces in header files? I know why importing a namespace in header file is pointless but what about a declaration like the above?

If the above one is the correct method, how do you do "forward declaration" of a class which is in another namespace? Is it like

#ifndef FOO_H
#define FOO_H
namespace AnotherNameSpace{
    class AnotherFoo; // forward declaration
}

namespace FooNameSpace{
    // Use AnotherFoo here
}
#endif

The "forward declaration" is the only method to avoid "cyclic dependency", correct?

Answer

Adam Rosenfield picture Adam Rosenfield · Jan 4, 2009
  1. The order of the include guards and the comments is purely a matter of style - it won't have any measurable effect on speed of compilation.

  2. Namespaces absolutely should be used in header files for declaring functions, classes, globals, etc. What you should not do is use using statements in header files -- it's impossible to unuse something in a source file that includes it, and you shouldn't force includers to add extra stuff to the global scope. If you need to use things from other namespaces in your headers, fully qualify every name. It can be a pain sometimes, but it's really the right thing to do.

Examples:

// WRONG!
using namespace std;
class MyClass
{
    string stringVar;
};

// RIGHT
class MyClass
{
    std::string stringVar;
};

As for forward declarations of classes in other namespaces, you've got it exactly right. Just remember to always qualify AnotherFoo as AnotherNameSpace::AnotherFoo when you reference it inside your header. Indeed, forward declarations are the only way to break cyclic dependencies.