Thomas M
Thomas M

Reputation: 47

Enumerations in C head files shared across multiple files

I want to define an enumeration type ONCE and have that type be shared across all the other files when I include the file, however I keep getting the following errors:

$ gcc -std=c99 main.c invoc.h invoc.c
main.c: In function ‘main’:
main.c:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘pr_alg’
main.c:12: error: ‘pr_alg’ undeclared (first use in this function)
main.c:12: error: (Each undeclared identifier is reported only once
main.c:12: error: for each function it appears in.)
main.c:13: error: ‘FIFO’ undeclared (first use in this function)
invoc.c:7: error: expected ‘)’ before ‘myalg’

The code is as follows:

invoc.h:

#define INVOC_H
#ifndef INVOC_H

typedef enum {FIFO, SECOND_CHANCE, RANDOM, NRU, CLOCK, AGING} alg_t;

void func1(alg_t myalg);

#endif

invoc.c:

#include "invoc.h"

void func1(alg_t myalg) {
    myalg = NRU;
}

main.c:

#include "invoc.h"

int main(int argc, char **argv) {

    extern alg_t pr_alg;
    pr_alg = FIFO;
    printf("PR_ALG: %d\n", pr_alg);

    return 0;
}

Is there any way that I can define an enumeration in a .h file, and include it in all other files so that I can both create different variables of that type and pass it to functions?

Upvotes: 2

Views: 1428

Answers (1)

KamilCuk
KamilCuk

Reputation: 141483

  1. You have an error in your invoc.h file:

    #define INVOC_H
    #ifndef INVOC_H
    ...
    #endif
    

    You first define a macro INVOC_H, then check if it does not exists (it does), so the code inside is removed by the preprocessor and not parsed by the compiler.
    It should be:

    #ifndef INVOC_H
    #define INVOC_H
    ...
    #endif
    

    After this change your code will work fine.

  2. You don't compile .h files, only .c files. That's why we put all definitions in .c files, and only declarations in .h files. To compile, just do:

    gcc -std=c99 mmu.c invoc.c
    
  3. You declare pr_alg in main() as extern variable. If the line you provided is the whole compilation line, the compile will issue linker error as variable pr_alg is nowhere defined. Remove extern or define variable pr_alg with global storage duration in one of the .c files.

Upvotes: 12

Related Questions