Typedef works for structs but not enums, only in C++

c, c++, enums, gcc, typedef

Solution

ISO C standard forbids forward references to `enum` types. I'm not completely sure, but I guess that this is the excerpt that confirms it:

6.7 Declarations

1 [...]

Constraints

2 A declaration shall declare at least a declarator (other than the parameters of a function or the members of a structure or union), a tag, or the members of an enumeration.

3 [...]

Please, if this is wrong, and you know which section exactly refers to the issue, correct me.

As a result, you are not allowed to use forward declarations of enumerations in C. Though, GCC allows it as an extension, but will certainly throw a warning if you enable `-Wpedantic` switch.

By the way, you could have written it like this:

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

and it is perfectly fine according to standard, and thus will compile even with `-Wpedantic -Werror`.

Problem

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.

Original source

Related problems