Abdus Salam Khazi Abdus Salam Khazi - 1 month ago 14
C Question

What happens when you redefine a macro?

#define MY_MACRO 3 --> in A.h
#define MY_MACRO 45 --> B.h





//In C.cpp

#include "A.h"
#include "B.h"


..
..
..

int my_value = MY_MACRO;





What will my_value be 3 or 45?

Answer

From the standard (draft) [cpp.replace] ยง2:

An identifier currently defined as an object-like macro (see below) may be redefined by another #define preprocessing directive provided that the second definition is an object-like macro definition and the two replacement lists are identical, otherwise the program is ill-formed. [...]


What happens when you redefine a macro?

When the new definition is different, your program is ill-formed. The compiler is required to show you a diagnostic message (a warning, or an error). The behaviour of an ill-formed program is not defined by the standard. The compiler is free to refuse compiling the program.

What will my_value be 3 or 45?

Whatever your pre-processor/compiler chooses. Or the compiler could refuse to compile it.


Technically, the program would become well-formed if you first undefined the macro. Then the defined value would obviously be the newly defined. However, I do not recommend this, because you can then easily break other rules depending on the order of inclusion of headers in multiple translation units.

Most likely, the two macros are supposed to be separate entities, and there are different files that expect the definition from one header, and not the other. The correct solution is to give each a unique name by renaming one, and change the dependant files to use the new name. Figuring out which files use which definition is may be a challenge. While you're at it, you may want to replace the macro with a constexpr variable.