ConfusedCheese
ConfusedCheese

Reputation: 141

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);
}

Upvotes: 4

Views: 31303

Answers (3)

hextor
hextor

Reputation: 21

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.

Upvotes: 2

Rohit
Rohit

Reputation: 152

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.

Upvotes: 1

natersoz
natersoz

Reputation: 1752

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

Upvotes: 10

Related Questions