C - forward declaration of enums?

loop picture loop · Sep 20, 2011 · Viewed 20.1k times · Source

Forward declaration of enums in C does not work for me. I searched the internet and stackoverflow but all of the questions regarding forward declarations of enumerators refer to c++. What do you do for declaring enumerators in C? Put them at the top of each file (or in an include) so that all functions in the file can access them? Thanks

Answer

Jonathan Leffler picture Jonathan Leffler · Sep 20, 2011

Put them in a header so that all files that need them can access the header and use the declarations from it.

When compiled with the options:

$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -c enum.c
$

GCC 4.2.1 (on MacOS X 10.7.1) accepts the following code:

enum xyz;

struct qqq { enum xyz *p; };

enum xyz { abc, def, ghi, jkl };

Add -pedantic and it warns:

$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -pedantic -c enum.c
enum.c:1: warning: ISO C forbids forward references to ‘enum’ types
enum.c:5: warning: ISO C forbids forward references to ‘enum’ types
$

Thus, you are not supposed to try using forward declarations of enumerated types in C; GCC allows it as an extension when not forced to be pedantic.