質問

In a C wrapper for a library (C++) I have the following code:

#ifndef _CWRAPPER_H__
#define _CWRAPPER_H__

// representation of a class inside the library:
typedef struct Foo Foo;  /* This compiles both with gcc and VS */

// representation of an enum inside the library:
typedef enum Bar Bar; /* gcc: "invalid type in declaration", VS compiles fine */

#endif  // _CWRAPPER_H__

Why is this declaration illegal in gcc but not in VS? How can I fix it?

I'm using VS 2010 and in a virtual machine Eclipse CDT with gcc 4.8.1.

EDIT: Apparently it has to be compiled as C++ to reproduce this error.


One workaround could be to declare it as:

typedef unsigned int Bar;

which does the trick if one provides all valid numbers Bar can take.

役に立ちましたか?

解決

A typedef needs a valid type. In the case of typedef struct Foo Foo, it doubles as a forward declaration of struct Foo, which satisfies the needs for the typedef. In the case of typedef enum Bar Bar, this doesn't work, since enums can't be forward declared.

Ref. eg. ISO/IEC 9899:1999 §6.7 :

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

— for an object, causes storage to be reserved for that object;

— for a function, includes the function body;98)

— for an enumeration constant or typedef name, is the (only) declaration of the identifier.

C++ has a similar constraint : Forward declaring an enum in c++.

It seems VS 2010 allows this as an extension.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top