Search code examples
c++macrosheader-filesredefinition

How do I generally avoid redefinition warnings?


I'm kind of a newbie to macro definitions, that's why I generally want to know: How do I avoid getting redefintion warnings?

I'm not sure if I'm correct but all I know is: Macro defintions are made in header files. If I include several header files into my source code that have the same macro defintions, I get a warning about a redefinition of a macro. A solution would be the removal of one of the includes in order to have only one macro definition. But what if I really need all the header files to let my program work correctly?

I also know that I can check whether macros are defined by using #ifdef or #ifndef but how and where do insert these checks? Into the header files? Or right before and after I included the header files?

As an example I have two warnings which tell me that the macros "__useHeader" and "__on_failure" are redefined, so how do I avoid these warnings?


Solution

  • How do I generally avoid redefinition warnings?

    The proper solution is to define any particular macro in exactly one header file - never more than one header. That header must of course use include guards.

    A solution would be the removal of one of the includes

    This is one approach. If you didn't need the definitions from that header, then it shouldn't be included anyway.

    But what if I really need all the header files to let my program work correctly?

    Another approach is to modify one or both of the header files.

    First check that each header uses an include guard. If not, add one.

    If both headers are intended to refer to the same macro, then

    • Remove the macro definition from one - let it be A.h - and include the one that still has the definition - let it be B.h - into A.h.

    • Or remove the macro definition from both, and move it into a third header and include that from both.

    • Or, if the macro is simply something that has to be defined, but the value isn't important, then in both headers only define the macro if it hasn't already been defined. This can be achieved with #ifndef

    If their macros have different meaning, and the naming is an accident, then rename one of the macros.


    If you do not wish to modify either header, then you must come into terms with the fact that those header files are incompatible with each other.

    If you don't have any function, or a class that depends on both headers (even indirectly), then you can work around the problem by separating definitions that depend on one header in separate translation units than definitions that depend on the other header. As soon as one definition depends on both, the headers must be fixed for compatibility.


    In general, avoid the use of macro definitions when variables or functions could be used instead. Put those variables and functions into namespaces to avoid name clashes.