Reputation: 131
Im compliling C code.
Say i have header file, A.h which contains an enum. I include this file in 2 c files - B.c and C.c
B.c:
#include A.h
//....other code...
C.c
#include A.h
//....other code...
When A.h contains an enum:
A.h
#ifndef A_H
#define A_H
enum my_enum {
//...enum content...
} my_enum;
//...other code...
#endif
when defined like this, i get a 'symbol "my_enum" multiply defined' error from the compiler, which is understandable- since i defined the enum in the header file.
However, this does not happen when i typedef the enum-
A.h
#ifndef A_H
#define A_H
typedef enum my_enum {
//...enum content...
} my_enum;
//...other code...
#endif
This of course happens regardless of what the code is in the .c files (other than including A.h)
What is the reasoning behind this? Why is it not a multiple definition when i typedef the enum?
Upvotes: 1
Views: 3133
Reputation: 4433
In C there are different name spaces.
We have this rules of "interference" (or not) of identifiers:
These name spaces are:
typedef
names and enumeration constants). enum
, struct
, union
tags. struct/union
members. goto
). Thus, for example, since typedef
names, enum
tagss, struct
members and labels are all in different name spaces, the following code has no any conflicts:
int main(void) // "x" is always in diffrent name spaces and/or scopes
{
typedef struct { struct { float x; } x; } x;
enum x { zero = 0 } value = zero;
x: // Label
if (value != 0)
goto x;
{ // This block is another scope
typedef enum x { one = 1 } x;
x w = one;
}
}
For reference, see Section 6.2.3 of C standard document: Standard C99, TC3
Upvotes: 1
Reputation: 1179
When you use typedef it will treat my_enum as just an alias of enum.
i.e. in that case my_enum behaves as a type and not a variable.
If you do not use typedef it will multiple declaration..
Upvotes: 0
Reputation: 122493
enum my_enum {
//...enum content...
} my_enum;
my_enum
here is not a type, but a variable of type enum my_enum
. Including this in a header leads to multiple definition of the variable my_enum
.
typedef enum my_enum {
//...enum content...
} my_enum;
my_enum
here is a type, not a variable. It's a type the same as enum my_enum
. That's the function of typedef
.
Upvotes: 4