Extern enum between different source files - C

19,757

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

Share:
19,757
ConfusedCheese
Author by

ConfusedCheese

Updated on June 27, 2022

Comments

  • ConfusedCheese
    ConfusedCheese almost 2 years

    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);
    }
    
    • 0___________
      0___________ over 6 years
      extern enum STATE state; -> extern STATE state;
    • ConfusedCheese
      ConfusedCheese over 6 years
      Thanks and tried. It still says 'undefined reference to state' unfortunately.
    • 0___________
      0___________ over 6 years
      so you probably do not link the object file with it
    • Jean-François Fabre
      Jean-François Fabre over 6 years
      extern STATE state; works fine indeed.
    • ConfusedCheese
      ConfusedCheese over 6 years
      Ah, my mistake, apologies. I am using PSOC creator. The source files do link correctly as the functions run into eachother as intended. Not sure how i specifically am not linking this part?
    • Julien
      Julien over 6 years
      not directly linked to the question but declare VS define stackoverflow.com/questions/1410563/…
    • ConfusedCheese
      ConfusedCheese over 6 years
      Figured out the problem. I needed to declare outside/above my main()