Search code examples
c++ifndef

Include Guards and #ifndef #define Preprocessing Statements


If I do the following:

dConst.hpp

const int POWER_LEVEL = 9001;

genPower.hpp

#include "dConst.hpp"

#ifndef GENPOWER_HPP
#define GENPOWER_HPP

const int GENERATOR[1] = { POWER_LEVEL };

#endif

I end up getting linker errors for any code that utilizes the generator array constant.

However, if I switch the #include "dConst.hpp" with the code block:

#ifndef GENPOWER_HPP
#define GENPOWER_HPP

It works...

Am I misusing the power of the #ifndef?


Solution

  • You are under-using the power of #ifndef.

    Your dConst.hpp file needs include guards. Otherwise, it will cause problems (the exact problems you saw) if it is included from more than one file within a translation unit.

    EDIT: I would also place your include guards in genPower.hpp at the top of the file, before your include statements.