Val
Val

Reputation: 325

C share multiple enums among different files

I apologize if my terminology is not perfect, I am a self taught programmer :) My automatic machine has different moving parts, and for each one I have a C file handling its own state machine. Each C file has an enum defining all the states for that state machine, for example:

movingArm.c

enum { 
    STANDBY = 0,
    ARM_OPEN,
    ARM_CLOSE,
    ARM_WAIT  
};


void state_machine_arm()
{
    switch(status_arm)
    {
        case STANDBY:
            // ....
        break;

        /* etc */
    }
} 

everything is running smoothly but sometimes I have to check the state of one state machine from another file, and so it would be handy to have all the enums in one common place to be accessed by all the files. Instead of every time checking what number corresponds to which states and having a huge risk of missing something.

So the question is: what's the best practice in this case? can all the enums be grouped in a single header file and included in all the .c files?

edit: I add some details, maybe I wasn't clear enough. If from another file anotherPart.c I want to check the status of the arm:

if( get_status_arm() == ARM_OPEN )
{
    // do something
}

I need to know what ARM_OPEN corresponds to, so ARM_OPEN should be defined also in anotherPart.c

This is why I thought about a common header file, to avoid re-declaring the enum in anotherPart.c (it would be even more annoying if I have to add or change something in the enum)

Upvotes: 1

Views: 830

Answers (1)

Lundin
Lundin

Reputation: 214265

So the question is: what's the best practice in this case? can all the enums be grouped in a single header file and included in all the .c files?

Yes, that would be the best practice. typedef enum { ... } arm_state_t; in a header file. Then in the same file provide a getter function which can return the internal state to those interested:

arm_state_t get_status_arm (void);

Also, as always, use include guards in the header. Creating your own header file in C

Upvotes: 3

Related Questions