2016-11-25 23 views
0

我繼續無法在以下(c)代碼中找到任何錯誤。然而,編譯器正在向我拋出錯誤。使用union時.c包含文件中的多個錯誤

這是

代碼FloatConverter.c

1 #ifndef FloatConverterh 
2 #define FloatConverterh 
3 
4 #include "FloatConverter.h" 
5 #include <stdint.h> 
6 
7 #define MAXVALUE 6000 
8 union Cast 
9 { 
10 double d; 
11 long l; 
12 }; 
13 
14 int32_t float2int(double d) 
15 { 
16  static volatile Cast cast; 
17 
18 cast.d = d + 6755399441055744.0; 
19 return cast.l; 
20 } 
21 
22 // naive 
23 int32_t f32ToInt16Digits(float f32) 
24 { 
25  return ((int32_t)(f32 * 2 * MAXVALUE/65535))); 
26 }; 
27 
28 // improved 
29 int32_t f32ToInt16Digits2(float f32) 
30 { 
31 return (float2int(f32 * 2 * MAXVALUE/65535)); 
32 }; 
33 
34 #endif 

FloatConverter.h

extern int32_t f32ToInt16Digits(float f32); 
extern int32_t f32ToInt16Digits2(float f32); 

我敢肯定,錯誤在於包含文件中。如果我刪除它(和所有參考),一切都恢復正常和良好。

這是由編譯器放出來的錯誤:

在FloatConverter.c

expected '=', ',', ';', 'asm' or '__attribute__' before 'cast' 16 
'cast' undeclared (first use in this function) 16 
expected ';' before ')' token 25 
expected statement before')' token 25 
在FloatConverter.h

expected '=', ',', ';', 'asm' or '__attribute__' before 'f32ToInt16Digits' 1 
expected '=', ',', ';', 'asm' or '__attribute__' before 'f32ToInt16Digits2' 2 

我現在沒有任何提示感謝。

+0

爲什麼在你的函數定義之後有分號?也是* FloatConverter.h *的全部內容?你不使用包括守衛?爲什麼在執行文件中包含警衛? –

+0

函數定義之後的分號是一個實驗,它們不會傷害任何我認爲的人。是的,它是整個文件。包含鎖定錯誤,但這不是錯誤的來源(測試它)。 – anyone

回答

0

您需要使用union聲明union Cast類型的變量這樣

union Cast cast; 

或創建一個類型,如以下

typedef Union Cast { ... } Cast; 

在此之後,你可以使用Cast castunion Cast cast兩者都應該編譯正確。

另外,包括像

衛士是爲了防止包括相同的文件多次,或者更確切地說,它的內容。他們不應該在.c實現文件中,因爲實現文件只能在程序中編譯一次,或者函數和全局變量的多個定義將阻止編譯成功。

最後,要與自己保持一致。如果要在左括號之後使用空格,並在對應的右括號之前使用空格,則請這樣做:總是 。但不要在一個地方做,然後在另一個地方省略它。

另一件事,你需要在出現int32_t之前包含stdint.h,這意味着它應該放在頭文件中的函數原型之前。在發佈的代碼中,只有在它之後才包含它,因此int32_t未在頭文件中定義,導致另一個編譯錯誤。


你真的不應該,它看起來可怕。

+0

謝謝!這消除了第16行中的兩個錯誤。好像有多個錯誤來源。 – anyone

+0

@a_random_Martin請閱讀我答案中的最後一段。 –

+0

我編輯它,我將在未來堅持下去:),此外在第二個定義的函數中有一個多餘的括號。謝謝你的時間!似乎今早我應該喝咖啡了...... – anyone