使用 union 时 .c 包含文件中的多个错误

Multiple Errors in .c include file while using 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

感谢任何提示。

您需要使用 union 声明类型为 union Cast 的变量,如下所示

union Cast cast;

或创建如下类型

typedef Union Cast { ... } Cast;

在此之后你可以使用 Cast castunion Cast cast 并且两者都应该正确编译。

此外,包括像

这样的守卫
#ifndef __THIS_INCLUDE_FILE_H__
#define __THIS_INCLUDE_FILE_H__

// Contents of the file

#endif // __THIS_INCLUDE_FILE_H__

旨在防止多次包含同一个文件,或者更确切地说是它的内容。它们不应该在 .c 实现文件中,因为实现文件只能在程序中编译一次,或者函数和全局变量的多个定义将阻止编译成功。

最后,与自己保持一致。如果您要在左括号后使用白色 space,在相应的右括号前使用白色 ALWAYS1。但是不要在一个地方做了,然后在另一个地方省略了。

另一件事,您需要在任何 int32_t 出现之前包含 stdint.h,这意味着它应该位于头文件中的函数原型之前。在发布的代码中,您仅在它之后包含它,因此 int32_t 在头文件中未定义,导致另一个编译错误。


1你真的不应该,它看起来很可怕。