[英]C Language: trouble using enumerated variable and type definited in main.c file inside another file
我在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 variabile和中斷處理程序內枚舉中列出的值,因此我將此聲明寫在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
類型的 extern
,因為另一個編譯單元需要知道其大小寫的值。 也就是說,將其放在標題中:
enum state_codes { S0,
// …
fsmError
};
並使用enum state_codes
包含所有文件的標頭。 變量仍然可以是extern
,例如extern enum state_codes cur_state
。
在.h
文件中鍵入def,然后在使用它的所有.c
文件中#include這個文件。
海事組織這是最正確的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.