简体   繁体   中英

C header file/ source file - enum typedef

If i got this declaration in my header file (.h)

typedef enum {START, END, STARTEMD, COMMENTS, DIRECTIVE} BalType;
typedef struct bal * Bal;

When i come in my .c (source file), i want to create my struct bal and include in it an attribute Baltype so i can tell later the type of bal. I've defined my struct like this :

struct bal {
    enum Baltype type;
    char * name;
    char * attrOne;
    char * attrTwo;
};

But i get the error : error: field type has incomplete type. I guess the error is on my typedef enum.

Thanks you.

First things first, a typedef creates a "first-class" type, where you shouldn't say it's an enumeration anymore when using it. The correct way is along the lines of:

typedef enum {A, B} C;
C c;                    // not enum C c.

Secondly, consider the following two segments:

typedef enum {A, B} C;
enum C D;

The first creates an untagged enumeration and also creates a type alias C for it. The second creates a separate tagged enumeration (tagged with C ) and creates no type alias (it also declares the variable D but that's not important for our considerations here).

Now you may be wondering what that has to do with your question but if we take the name that you used when creating the type, and place below it the name you used within the struct , I would hope it would become apparent:

BalType
Baltype
   ^
   An extra clue :-)

So the simplification of your problem is thus remarkably similar to the ABCD code I gave above:

typedef enum {START, END} BalType;
enum Baltype type;

It's actually the combination of those two things giving you grief. You seem to be creating a complete enumerated type, and you are. However, you then create a totally different (and incomplete, since it has no body) enumeration. Being incomplete, it cannot be used in the manner you need.

To solve it, the final line above (and the first within your struct ) should be replaced with:

BalType type;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM