a_random_Martin a_random_Martin - 1 year ago 84
C Question

Multiple Errors in .c include file while using union

I continuingly fail to find any error in the following (c)code. Yet the compiler is throwing errors on me.

This is the code in


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


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

I'm sure the error lies within the include file. If I remove it (and all refrences) everything is back to normal and fine.

This are the errors that are put out by the compiler:

In 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

in FloatConverter.h:

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

I'm grateful for any hints.

Answer Source

You need to use union to declare a variable of type union Cast like this

union Cast cast;

or create a type like the following

typedef Union Cast { ... } Cast;

after this you can use Cast cast or union Cast cast and both should compile correctly.

Also, include guards like


// Contents of the file

#endif // __THIS_INCLUDE_FILE_H__

are meant to prevent including the same file multiple times, or rather it's content. They should not be inside a .c implementation file because implementation files can only be compiled once in a program or multiple definitions of functions and global variables will prevent compilation from succeeding.

Finally, be consistent with yourself. If you are going to use white space after an opening parenthesis and one before the corresponding closing parenthesis then do it so ALWAYS1. But don't do it in one place and then omit it in another.

Another thing, you need to include stdint.h before any occurrence of int32_t and that means, it should go before the function prototypes in your header file. In the posted code, you include it only after it and hence int32_t is undefined in the header file causing the another compilation error.

1You really shouldn't, it looks horrible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download