Why don't I get 'Multiple Definitions' of enum in C?

c, enums

Solution

An enumeration will not create a value in memory, which means there is no address added to the symbol table when linking.

A const variable will have an address in the compiled object, with a symbol name. When you try to link the two object files together, they each have the same symbol name "RED" pointing to different addresses, which is what causes your conflict.

Problem

Let's say I have three files: ``` //m.h const int RED = 1; //m.h ends here //f1.c #include "m.h" //f1.c ends here //f2.c #include "m.h" int main() {return 0;} //f2.c ends here ``` Compiling each one separately will work, but `gcc -Wall f1.o f2.o -o prog` will produce: `multiple definition of 'RED'` Now if I replace the const with: ``` //m.h enum {RED=1} colors; //m.h ends here ``` I'll be able to compile `prog` and use `RED` as a const and won't get any `multiple definition` error. Why is the behavior with `enum`s different from the one visible when you have global variables or structs with the same name in different files?

Original source