I have the following code:
test_header.h:
typedef enum _test_enum test_enum;
enum _test_enum
{
red,
green,
blue
};
typedef struct _test_struct test_struct;
struct _test_struct
{
int s1;
int s2;
int s3;
};
test.c:
#include <test_header.h>
#include <stdio.h>
int main()
{
test_struct s;
s.s1=1;
s.s2=2;
s.s3=3;
printf("Hello %d %d %d\n", s.s1, s.s2, s.s3 );
}
test_cpp.cpp:
extern "C"{
#include <test_header.h>
}
#include <stdio.h>
int main()
{
test_struct s;
s.s1=1;
s.s2=2;
s.s3=3;
printf("Hello %d %d %d\n", s.s1, s.s2, s.s3 );
}
Notice how I am typedef'ing the struct and the enum the same way. When I compile in straight C with gcc -I. test.c -o test
it works fine, but when compiled in C++ with gcc -I. test_cpp.cpp -o test_cpp
, I get the following error:
./test_header.h:1:14: error: use of enum ‘_test_enum’ without previous declaration
So my question is twofold: why does this work in C but not C++, and why does the compiler accept the struct but not the enum?
I get the same behavior when declaring the struct above the enum. I'm using GCC 4.8.2.
An introduction to C Enumerated TypesUsing the typedef and enum keywords we can define a type that can have either one value or another. It's one of the most important uses of the typedef keyword. This is the syntax of an enumerated type: typedef enum { //...
A typedef is a mechanism for declaring an alternative name for a type. An enumerated type is an integer type with an associated set of symbolic constants representing the valid values of that type.
typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.
The enum is an integral type and the compiler chooses the exact type according to the range of values of the enumeration. So you can't do a forward declaration of an enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With