gcc 4.4.4 c89
I have the following in my state.c file:
enum State {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
};
State g_current_state = State.IDLE_ST;
I get the following error when I try and compile.
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘g_current_state’
Is there some with declaring a variable of type enum in global scope?
Many thanks for any suggestions,
typedef enum { IDLE_ST, START_ST, RUNNING_ST, STOPPED_ST, } State; State g_current_state = IDLE_ST; I prefer the second one since it makes the type look like a first class one like int . Show activity on this post. State by itself is not a valid identifier in your snippet.
It's not treated as a global variable. It's treated as a global identifier. More precisely, it's treated as an identifier in whatever namespace the enum is declared in.
C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn't allow implicit conversion to int, and also doesn't compare enumerators from different enumerations. To define enum class we use class keyword after enum keyword.
In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.
There are two ways to do this in straight C. Either use the full enum
name everywhere:
enum State {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
};
enum State g_current_state = IDLE_ST;
or (this is my preference) typedef
it:
typedef enum {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
} State;
State g_current_state = IDLE_ST;
I prefer the second one since it makes the type look like a first class one like int
.
State
by itself is not a valid identifier in your snippet.
You need enum State
or to typedef the enum State
to another name.
enum State {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
};
/* State g_current_state = State.IDLE_ST; */
/* no State here either ---^^^^^^ */
enum State g_current_state = IDLE_ST;
/* or */
typedef enum State TypedefState;
TypedefState variable = IDLE_ST;
Missing semicolon after the closing brace of the enum
. By the way, I really do not understand why missing semicolon errors are so cryptic in gcc.
So there are 2 problems:
;
after enum
definition.enum State
instead of simply State
.This works:
enum State {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
};
enum State g_current_state;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With