Typedef works for structures, but does not list, only in C ++

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 typify the structure and enumeration in the same way. When I compiled in direct C with gcc -I. test.c -o test gcc -I. test.c -o test , it works fine, but when compiled in C ++ with gcc -I. test_cpp.cpp -o test_cpp 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 it work in C, but not in C ++, and why does the compiler accept a structure, but not an enumeration?

I get the same behavior when declaring a structure over an enumeration. I am using GCC 4.8.2.

+7
c ++ c gcc enums typedef
source share
2 answers

The ISO C standard prohibits direct references to enum types. I'm not quite sure, but I think this is an excerpt confirming this:

6.7 Announcements

one [...]

Limitations

2 At least a declarator is declared in the declaration (except for function parameters or elements of a structure or association), a tag or enumeration members.

3 [...]

Please, if this is not the case, and you know which section relates exactly to the problem, correct me.

As a result, you are not allowed to use forward enumeration declarations in C. Although GCC allows it as an extension, it certainly gives a warning if you enable the -Wpedantic switch.

By the way, you could write it like this:

 typedef enum { red, green, blue, } test_enum; 

and it perfectly conforms to the standard and thus will even compile with -Wpedantic -Werror .

+5
source share

An enumeration is an integral type, and the compiler selects the exact type according to the range of values โ€‹โ€‹of the enumeration. Thus, you cannot redirect rename.

+6
source share

All Articles