This question is a searching for robust approach to prevent such errors in existing and new projects. A code bellow illustrate the problem. GCC compiler show warning only if macro are conflicts but when it enum vs macro - no.
I can't found gcc -Wxxx options to get warnings for such conflicts.
- It's possible to use macro with
__COUNTER__
instead of enum. - It's possible to change format rules for enum names.
But it's helpful solutions only for new projects.
What I can do with old projects ?
enum my_enum {
NONE = -1,
// #define NONE -1
ONE = 1,
TWO,
THREE,
};
// use name NONE something else in included header
#define NONE 2
#include "stdio.h"
int main(void)
{
printf("NONE is %d, it's %s\n",
NONE,
(-1 == NONE) ? "OK" : "FAIL");
return 0;
}
So result with commented macro NONE -1
:
gcc ./c-test.c -o c-test && ./c-test
NONE is 2, it's FAIL
And uncommented.
gcc ./c-test.c -o c-test && ./c-test
./c-test.c:11: warning: "NONE" redefined
11 | #define NONE 2
|
./c-test.c:4: note: this is the location of the previous definition
4 | #define NONE -1
|
Env:
- Linux 5.4.0-132-generic #148-Ubuntu
- gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0