C Language : trouble using enumerated variable and type definited in main. c文件在另一个文件里面

标签 c enums global

我在 main.c 文件中定义了以下枚举和变量:

enum state_codes {  S0,
        S1,
        S2,
        S3,
        S4,
        S10,
        S20,
        S30,
        S40,
        S50,
        S60,
        S70,
        S80,
        fail,
        fsmError
};

enum state_codes cur_state = S0;
enum state_codes old_state = S0;

进入我的项目的另一个文件(名称为 othercode.c)我必须使用 cur_state 变量和中断处理程序中枚举中列出的值,所以我在 othercode.c 文件的顶部写了这个声明:

extern enum state_codes; // <-- first warning see below details
extern enum state_codes cur_state;

在中断处理程序中我写了这段代码:

void EXTI4_IRQHandler(void)
{
     EXTI_ClearITPendingBit(EXTI_Line4);

    // FSM state saving inside the external EEPROM
    // cur_state : current state from the main.c file
    uint8_t data_byte;

    if (cur_state == S0) // <-- ERRORS see below details
    {
      data_byte = 0;
    }

    I2C_Memory_Write(I2C1, EE_ADDR_FSMSTATE, data_byte);

}

关于此功能,我收到以下警告和错误报告:

Warning[Pe1000]: a storage class may not be specified here C:\Users\ ... \othercode.c 49 

Error[Pe020]: identifier "S0" is undefined C:\Users\ ... \othercode.c 777 

Error[Pe070]: incomplete type is not allowed C:\Users\ ... \othercode.c 777 

第一个警告与声明有关:

extern enum state_codes;

另外两个函数错误发生在我用 <-- 错误标记到代码中的那一行。

我需要做的是在另一个文件中引用枚举类型变量,因此我已将其声明为外部文件,但似乎可以通过这种方式处理这种类型的存储类。 有人可以指出我正确的方向吗?

已编辑

我通过将枚举重新声明到另一个文件中解决了这个问题,如下所示:

enum state_codes {  S0,
        S1,
        S2,
        S3,
        S4,
        S10,
        S20,
        S30,
        S40,
        S50,
        S60,
        S70,
        S80,
        fail,
        fsmError
};
extern enum state_codes cur_state;

代码工作正常,但我想问一下这是正确的方法还是需要考虑其他一些事情。

谢谢!

最好的问候 火

最佳答案

你不能自己定义enum type extern,因为其他编译单元需要知道的值它的案例。也就是说,将其放在标题中:

enum state_codes {  S0,
        // …
        fsmError
};

并使用 enum state_codes 包含所有文件的 header 。变量仍然可以是extern,比如你的extern enum state_codes cur_state

关于C Language : trouble using enumerated variable and type definited in main. c文件在另一个文件里面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959242/

相关文章:

c - 在c中使用字符串指针

c - 有没有办法用 2 个信号量来解决生产者-消费者问题?

swift - switch 语句中 case 的顺序重要吗?

python - 共享资源时如何避免python线程中的全局?

python 字符串默认是全局的

c - C语言任务提醒程序

c - 用于收集参数的 Bison 语法

c++如何在不同的枚举名称中具有相同的枚举成员名称而不会出现错误:redefinition; previous definition was 'enumerator'

c++ - 如果枚举不能放入整数类型会发生什么?

c++ - 工厂模式与全局状态不是一回事吗?