Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum declaration in header file

I have files A.c , B.c and B.h . In A.c there is an

enum CMD{
    FIRST,
    SECOND,
    THIRD,
};

and later in that file there is

bool function(...){
//...
enum CMD data_type = FIRST;
//...
}

In file B.c I need to use

if (data_type == FIRST){...}

I tried to include in B.h this:

extern enum CMD data_type;

And included #include "B.h" in A.c and B.c . All files are in the propper folders of the project. But no cigar :( The line in B.c gives this:

20: identifier "FROM_SMS" is undefined
70: incomplete type is not allowed

How do I make this work. The A.c file is writen by someone else and I'm modifiing the code with B.c . The original code is a mess and I wan to fidlle with it as less as possible :) Architecture ie STM32 and I'm using uVision 3 IDE.

Thank you

like image 331
Jonas K Avatar asked Oct 30 '25 11:10

Jonas K


1 Answers

An enum is a type, you should put in in the .h.

extern keyword is for variables.

Edit: Sorry, I had badly read your code.

Here the problem is that you will try to use the enum without having it defined. Think that when a compiler compiles something, it takes every .c file separately, and then "copies" the content of the include into the c file.

So here you will have b.c which includes b.h but since the declaration of your type is in a.c, the compiler has no way of knowing it, hence throwing an error when trying to compile b.c.

To solve it, just declare your type at the top of b.h and include it in both files, or create a "myenum.h" file which you include in the .h / .c files that require it.

like image 194
Jean-Michaël Celerier Avatar answered Nov 02 '25 00:11

Jean-Michaël Celerier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!