declaring enum in global scope
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 ‘=’, ‘,’, ‘;’, ‘as开发者_开发问答m’ or ‘__attribute__’ before ‘g_current_state’
Is there some with declaring a variable of type enum in global scope?
Many thanks for any suggestions,
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:
- Missing
;
afterenum
definition. - When declaring the variable, use
enum State
instead of simplyState
.
This works:
enum State {
IDLE_ST,
START_ST,
RUNNING_ST,
STOPPED_ST,
};
enum State g_current_state;
精彩评论