2

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);
}
ConfusedCheese
  • 121
  • 1
  • 1
  • 3

3 Answers3

10

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

natersoz
  • 1,674
  • 2
  • 19
  • 29
  • Isn't it generally quite strange for a main.c file to have a header file? The main file doesn't (and shouldn't) generally have any info that needs to be exposed for the linker or startup code to work. – Milind Sharma Jul 20 '22 at 07:50
1

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.

hextor
  • 11
  • 1
0

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.

martin
  • 2,520
  • 22
  • 29
Rohit
  • 142
  • 8