【问题标题】:declaring enum in global scope在全局范围内声明枚举
【发布时间】:2010-11-04 10:30:36
【问题描述】:

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’

有没有在全局范围内声明枚举类型的变量?

非常感谢您的任何建议,

【问题讨论】:

    标签: c


    【解决方案1】:

    State 本身不是您的 sn-p 中的有效标识符。

    您需要enum State 或将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】:

      在直接 C 中有两种方法可以做到这一点。在任何地方都使用完整的 enum 名称:

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

      或者(这是我的偏好)typedef它:

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

      我更喜欢第二个,因为它使类型看起来像 int 这样的第一类。

      【讨论】:

        【解决方案3】:

        enum 的右大括号后缺少分号。顺便说一句,我真的不明白为什么缺少分号错误在 gcc 中如此神秘。

        【讨论】:

        • 不,这不是原因。我仍然收到错误消息。谢谢
        【解决方案4】:

        所以有2个问题:

        1. enum 定义之后缺少;
        2. 声明变量时,使用enum State 而不是简单的State

        这行得通:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-18
          • 2017-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多