ant2009
ant2009

Reputation: 22486

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 ‘=’, ‘,’, ‘;’, ‘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,

Upvotes: 7

Views: 17271

Answers (4)

lemic
lemic

Reputation: 197

So there are 2 problems:

  1. Missing ; after enum definition.
  2. When declaring the variable, use enum State instead of simply State.

This works:

enum State {
    IDLE_ST,
    START_ST,
    RUNNING_ST,
    STOPPED_ST,
};

enum State g_current_state;

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881383

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.

Upvotes: 19

pmg
pmg

Reputation: 108978

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;

Upvotes: 3

Luca Martini
Luca Martini

Reputation: 1474

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.

Upvotes: 2

Related Questions