Why don't enums in multiple source files cause a link error?

Viewed 59

0.c

typedef enum nums{
 i = 1, j=2
} nums;
// int k = 5; <-- commented out

int main(){
 return i;
}

1.c

typedef enum nums{
 i = 1, j=2
} nums;
// int k = 5; <-- commented out

If I compile the above with gcc 0.c 1.c I don't get a link error, however, if I uncomment k I will get an error.

2 questions:

1 - How come enums are immune from link issues, aren't i and j just another int?

2- What happens if enums with same name have different values in different translation units? undefined behaviour?

1 Answers
  1. The enum defines an enumerated type. The identifiers are integer constants. Types are not linked, nor are these enumeration constants. Only objects and functions, and among them only those that have external linkage are considered for linking.

  2. Nothing in particular, except that they're not compatible types. However if you try to use the two interchangeably then and only then the behaviour is undefined.

Related