2016-11-25 65 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