Sign in to follow this  
tekmoto

Using extern with enums in C++

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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_H

enum 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[i]=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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this