Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef works for structs but not enums, 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 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.

like image 610
monkeypants Avatar asked Nov 22 '13 17:11

monkeypants


People also ask

Can you typedef an enum in C?

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 { //...

What is the use of typedef and enum in C?

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.

Should I typedef structs in C?

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.

Does struct need typedef?

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.


1 Answers

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.

like image 135
jdc Avatar answered Sep 17 '22 08:09

jdc