Using extern with enums in C++

Started by
2 comments, last by bakery2k1 17 years, 7 months ago
Does anyone know how to use the "extern" declaration correctly for constants and enums? This is generally what I had in mind, but turns out to be incorrect. In the header file (e.g., something.h), I would have:
extern const int NUM_PEOPLE;

extern enum State;
extern State Person[NUM_PEOPLE];
In the source file (e.g., something.cc), I would have:
const int NUM_PEOPLE = 314;

enum State 
{
   Happy,
   Sad,
   Mad
};

State Person[NUM_PEOPLE];
Something like this would not compile. Why not?
Advertisement
The enum values need to be available to the compiler when it is compiling code that uses them, so you can't isolate them out into a .cpp file like that.

Just declare the enum values in the .h file. As long as you have header guards so it can't be included in any one unit more than once, it will be fine.

I can't see a problem with the const int though. Does it compile if you take the extern-ed enumeration out?

Oh, and to extern your array of states, do this (actually, all the code):

states.h
#ifndef STATES_H#define STATES_Henum State { happy,sad,mad };extern const int NUM_PEOPLE;extern State Person[]; // do not provide the size here#endif


state.cpp
#include "state.h"const int NUM_PEOPLE=300;State Person[NUM_PEOPLE];


Another unit can now include state.h, link to state.obj and access the Person array and NUM_PEOPLE constant.

main.cpp
#include "state.h"int main(){    for(int i=0;i<NUM_PEOPLE;++i) Person=happy;    return 0;}


If the enum values were defined inside state.cpp, they would not be available to the compiler when it was compiling main.cpp so the above code could not possibly work. You can have a local enum inside a .cpp that is only used in that unit, but this is why you could not extern an enum as you have attempted to do.

HTH Paul
Ah, now I know the correct usage. And yes, that worked perfectly!

Thank you.
You could also put the const int into the header file.

By default const integers are "static", so the constant will be defined separately in each compilation unit, but will not be exported so linking will still succeed.

This topic is closed to new replies.

Advertisement