How do we have extern for a member of enum

how to have extern for a member of enum

tried int type of it failed as it's used in a cpp including an .h :
1
2
3


extern STATES TO_STATE;



has definition in some .cpp

1
2
3
4
5
enum STATES {
	BEGIN_STATE,
	TO_STATE
};


its user:
 
int arraySTATE[TO_STATE];


is failing.. How to solve using it for extern as working normally well as other builtin types ?
Last edited on
I think you need to replace:
extern STATES TO_STATE;

with this:
enum STATES;

And then in cpp file before using the enum you need full definition of the enum.

is failing.. How to solve using it for extern as working normally well as other builtin types ?

AFAIK, You can't.
Move the enum def into a header and then include that header where you need the enum

header.hpp
1
2
3
4
5
6
#ifndef __HEADER_HPP__
#define __HEADER_HPP__

enum STATES { BEGIN_STATE, TO_STATE, END_STATE };

#endif 

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "header.hpp"

void func();

int main()
{
   STATES state = END_STATE;

   std::cout << state << '\n';

   func();
}

file.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "header.hpp"

void func()
{
    STATES hello = BEGIN_STATE;

    std::cout << "func(): " << hello << '\n';
}
Note that you can't actually forward declare (regular) enums in Standard C++. This is because the compiler is allowed to decide based on the values of the enum members what integral type is required to represent a particular enum, which it can't decide on without knowing the members.

Some compilers do let you get away with a forward declaration. But it's not valid Standard C++.

You are allowed to forward declare the new enum class, though.

Andy

PS Further reading:

Forward declaring an enum in C++
https://stackoverflow.com/questions/71416/forward-declaring-an-enum-in-c
Last edited on
Any enum can be forward-declared when its underlying type is specified or known.

This doesn't mean you can just use enumerators before they've been defined.
Last edited on
Topic archived. No new replies allowed.