extern enum in c++

和自甴很熟 提交于 2019-12-03 13:05:41

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.

You cannot use enum values, if they are not visible. If the header is too large to include, why not just put the enum in its own header, and include only that?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!