C Defining an enum in one header file and using that enum as a function parameter in another file

时间:2016-07-11 22:05:36

标签: c enums

I have defined an enum in a header file, global.h:

Typedef enum
{
    ELEMENT1,
    ELEMENT2,
    ELEMENT3
}e_element;

I have a second file using the enum as a function parameter. file2.c

#include global.h
#include file2.h
Function(e_element x)
{
Body…
}

The prototype is in: file2.h

Function(e_element x);

The compiler doesn’t know e_element in file2.h. I have tried putting the #include for global.h in both file2.c and file2.h, but it still doesn’t see it. I would put the enum in file2.h, except that it is used by several other files, so if I move it the problem will just show up somewhere else. How can I get the file2.h prototype to see e_element?

1 个答案:

答案 0 :(得分:3)

This worked for me:

global.h

#ifndef GLOBAL_H
#define GLOBAL_H

typedef enum
{
    ELEMENT1,
    ELEMENT2,
    ELEMENT3
}e_element;

#endif

file2.h

#ifndef FILE_2_H
#define FILE_2_H

#include "global.h"
int test(e_element);

#endif

file2.c

#include "file2.h"

int test(e_element x)
{
    return x == ELEMENT1;
}

int main() {
    return 0;
}

edit: #ifndef is conventionally used as a "header guard". It prevents a header file from being included multiple times by the preprocessor, which prevents things from being defined multiple times. It works by checking if a unique symbol has been defined before. If it has not, then it immediately defines it and then continues with the header file until #endif. If the symbol was already defined then it skips the guarded code completely, preventing multiple definitions. An example of multiple definitions would be if the same header file was included in a source and a header that the source also includes.

See this link for more information.