Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern enum between different source files - C

I am having trouble with accessing an enum defining the state of a program between multiple source files.

I define my enum in my header main.h

    typedef enum{ 
    STATE_HOME,
    STATE_SETUP,
    }STATE;

extern enum STATE state;

I declare it in my main.c

#include "main.h"
STATE state = STATE_HOME;

but when I try and use it in another source file, example.c, it says 'undefined reference to state':

#include "main.h"
void loop ()
{
UART(state);
}
like image 807
ConfusedCheese Avatar asked Sep 02 '25 17:09

ConfusedCheese


1 Answers

The quickest solution to your problem is to change your enum to this:

typedef enum STATE {
    STATE_HOME,
    STATE_SETUP,
} STATE;

But personally, I hate typedef-ing things in the C language, and as you have already noticed: naming confusion.

I think a more preferable method is merely this:

-- main.h:

enum STATE {
    STATE_HOME,
    STATE_SETUP,
};


extern enum STATE state;

-- main.c:

enum STATE state = STATE_HOME;

This avoids the entire conversation about different C language namespaces for typedef.

Apologies for a terse answer without more explanation...

like image 83
natersoz Avatar answered Sep 04 '25 11:09

natersoz