emesx
emesx

Reputation: 12755

Should you use #ifndef guard in forward declaration headers?

I have a simple header file where I forward-declare all classes in a namespace, eg.

#ifndef TEST_FWD_HPP
#define TEST_FWD_HPP

namespace a {
    namespace b {

            class A;
            class B;

    }
}

#endif

Should this file be guarded against multiple includes (#ifndef ...) ? Does this make sense for forward declarations only?

Upvotes: 3

Views: 705

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

Just use a (formally non-standard) #pragma once and be done with it.

In addition to preventing multiple inclusions in the same translation unit, header guards or a #pragma once let the savvy compiler avoid re-scanning the file.

Upvotes: 2

tomahh
tomahh

Reputation: 13661

Multiple include guard don't only serve multiple declaration errors. You need to insert those guards in every header file, to avoid infinite inclusion loop.

Upvotes: 2

Julian
Julian

Reputation: 852

It's usually good practice to protect header files like this. It isn't necessary in most cases where the file is only included once, but when a project gets complex, and header files are included in other header files it can help keep you sane.

If you only have forward definitions and function prototypes in it, then it usually isn't necessary, but as header files tend to acrete stuff over time, it's often worth doing as a matter of course.

Upvotes: 5

Related Questions