2
votes

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);
}
3
extern enum STATE state; -> extern STATE state;0___________
Thanks and tried. It still says 'undefined reference to state' unfortunately.ConfusedCheese
so you probably do not link the object file with it0___________
extern STATE state; works fine indeed.Jean-François Fabre
Figured out the problem. I needed to declare outside/above my main()ConfusedCheese

3 Answers

7
votes

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

0
votes

Extern is a way to use global variable in multiple files. Simple approach of extern is:

  • Declare extern varaible: This should be done in header file. For ex: in STATE_Declaration.h:
typedef enum{ 
    STATE_HOME,
    STATE_SETUP,
} STATE;

extern STATE state; /*Extern Declaration (NOTE:enum is not needed )*/
  • Extern variable definition: in STATE_definition.c
    #include "STATE_Declaration.h"
    STATE state = STATE_HOME;
  • and finally, usage: in STATE_USAGE.c
#include "STATE_Declaration.h"
void loop ()
{
    UART(state);
}

These 3 things should be taken care of, then nothing will fail w.r.t extern.

0
votes

An alternative method to share the constant values (of enum members) among multiple source files:

enums.h:
enum { STATE_HOME, STATE_SETUP }; // anonymous enum (no name tag)

main.c:
#include "enums.h"

example.c:
#include "enums.h"

Access to the enum members is as if they were defined using preprocessor "#define" statements; so use the member names alone, like int variables.

printf ("values of STATE_HOME: %d and STATE_SETUP: %d \n", STATE_HOME, STATE_SETUP);

How it works:

The enum members are cloned versions, replicated and made available in each source file that includes the enums.h header file. This is possible using the static specifier. This works when only static declarations or definitions populate the header file.