0

I am currently trying to use two headers defining (partially) the same constants. Typically the constants should be the same but my plan is to add a check to be absolutely sure. The problem can be described by the following minimal example:

#include "header1.h" //Defines MY_CONSTANT 99
#include "header2.h" //Also defines MY_CONSTANT 99

Compiling is possible but the warning

warning: "MY_CONSTANT" redefined

should not be ignored since I want to be sure both headers are defining the same value.

My plan was to undef the define before including the second header with checking the values are equal. I've tried to save the first value of the constant as C++ const and added a static assertion but it seems like the compiler is not doing what I need:

#include "header1.h" //Defines MY_CONSTANT 99
const uint64_t MY_CONSTANT_OLD = MY_CONSTANT;
#undef MY_CONSTANT
#include "header2.h" //Defines again MY_CONSTANT 99
static_assert(MY_CONSTANT_OLD == MY_CONSTANT, "Redefined with other value"); //Check same definition

MY_CONSTANT’ was not declared in this scope

How could I solve the problem of redefining the constants with getting a compiler error if the values are not equal?

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • Do you have control over the headers? If so I would just move the constants to their own header (as an `inline constexpr` if you can use C++17) and then include that header in headers. – NathanOliver Aug 14 '19 at 13:22
  • Unfortunately I am not able to do any changes in the headers. – Fruchtzwerg Aug 14 '19 at 13:24
  • How is `MY_CONSTANT` defined in the headers? – 1201ProgramAlarm Aug 14 '19 at 13:25
  • It is defined like `#define MY_CONSTANT 99` – Fruchtzwerg Aug 14 '19 at 13:26
  • 2
    Is there a `#if` conditional around the definition in `header2`? That second error message doesn't make sense if `MY_CONSTANT` is defined as a macro. – 1201ProgramAlarm Aug 14 '19 at 13:38
  • Of course @1201ProgramAlarm - this was a very good hint. There is a include guard added. Since I am including the header several times in my project, the redefine is only done once. Looks like I need to do the check only at first include. Is there a simple way to ensure this? – Fruchtzwerg Aug 14 '19 at 13:51
  • 1
    How can I put it kindly... Don't. If you have two APIs (each of them defined in one of two headers you cannot control) which conflict in some or even one of their identifiers, then do not include both into one file. Split the including file in one part which uses one API and one part which uses the other. If the two parts need to communicate, then define your own, clean API betwenn them and communicate cleanly across the clean border. – Yunnosch Aug 14 '19 at 14:10
  • The error says that the constant is not defined in header2 or header1 - depending on error line. – Robert Andrzejuk Aug 14 '19 at 16:41

0 Answers0