I have an enum I have declared in some .h file:
typedef enum {
NONE,
ONE,
TWO,
THREE
} MYENUM;
in a seperate .cpp I cannot do this:
extern enum MYENUM; //works
extern MYENUM TWO; //makes sence, TWO is not an INSTANCE of MYENUM...
how would one do so without including the whole header where the enum is declared?
You can't use an incomplete type. You can only pass around pointers to it. This is because until the type is completed, the compiler doesn't know how big it is. OTOH a pointer is the size of a data pointer, no matter what type it's pointing to. One of the things you can't do with an incomplete type is declare variables of that type.
extern
in a variable declaration means that the compiler will emit a reference to an identifier provided in another compilation unit (to be resolved by the linker), instead of allocating storage. extern
does not modify the type, even if it appears next to the type name in C++ grammar.
What you can do is take advantage of the fact that enum members are integral constant values, and convert just fine to the primitive integral types.
So you can do this:
A.cpp
enum MYENUM { ONE=1, TWO, THREE };
int var = TWO;
B.cpp
extern int var;
But the types must match. You couldn't say MYENUM var = TWO;
and also extern int var;
. That would violate the one-definition-rule (violation might or might not be detected by the linker).
As an aside, this is incorrect:
typedef enum {
NONE,
ONE,
TWO,
THREE
} MYENUM;
enum MYENUM TWO;
MYENUM
is NOT an enum identifier. It is a typedef, and cannot be qualified with the enum
keyword later.