2010-11-04 137 views
6

GCC 4.4.4的C89在全球範圍內宣佈枚舉

我在state.c文件中的以下內容:

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

State g_current_state = State.IDLE_ST; 

我收到以下錯誤,當我嘗試編譯。

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘g_current_state’ 

是否有一些在全局範圍內聲明枚舉類型的變量?

非常感謝您的任何建議,

回答

19

有兩種方法可以做到這一點直C.無論是使用全enum名無處不在:

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

或(這是我的偏好)typedef it:

typedef enum { 
    IDLE_ST, 
    START_ST, 
    RUNNING_ST, 
    STOPPED_ST, 
} State; 
State g_current_state = IDLE_ST; 

我更喜歡第二個,因爲它使得式看起來像一個一流的人喜歡int

+0

+1,喜歡第二個。 – 2010-11-04 11:03:52

2

enum的右括號後缺少分號。順便說一句,我真的不明白爲什麼在gcc中缺少分號錯誤是如此神祕。

+0

不,那不是理由。我仍然收到錯誤。謝謝 – ant2009 2010-11-04 10:42:03

2

State本身是不是在你的代碼段是有效的標識符。

你需要enum State或在的typedef到enum State另一個名字。

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; 

/*或*/

typedef enum State TypedefState; 
TypedefState variable = IDLE_ST; 
2

因此,有2個問題:

  1. enum定義缺少;
  2. 當聲明變量,使用enum State而不是簡單地State

這工作:

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

enum State g_current_state;