Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ extern enums

Tags:

c++

enums

extern

i found already this: extern enum in c++ But it didn't helped me much. I have a config.h and a config.cpp in the config.h i have my enum:

#ifndef CONFIG_H
#define CONFIG_H
extern enum Items;
#endif

And in my config.cpp i have the enum declared:

#include "config.h"
 enum Items {
    PAC = 'C', GHOST = '@', FRUIT = 'o', POINTS = '.', WALL = '#', EMPTY = ' ', UNDEFINED = '+'
} fieldItems;

But if i try to compile it the compiler gives me the following Errors:

config.cpp:20:13: error: a storage class can only be specified for objects and functions
 extern enum Items;
         ^
like image 955
AnnoyedGuy Avatar asked Jan 31 '26 07:01

AnnoyedGuy


1 Answers

You won't be able to define an enum externally. In C++11 you can forward declare an enum, however:

enum class Items: char;

... and later define it:

enum class Items: char {
       PAC = 'C', GHOST = '@', FRUIT = 'o', POINTS = '.', WALL = '#', EMPTY = ' ', UNDEFINED = '+'
};

Note, however, that you can use the enumerator tags only where the definition was seen.

Based on your comment about multiple definitions, you don't have include guards in your header and the same header gets included multiple times. That is, seems you could have a header something like this:

// items.h
#ifndef INCLUDED_ITEMS
#define INCLUDED_ITEMS

enum Items { ... };

#endif

From the looks of it, you are trying to fold the representation of the game into into the definition of their names. That probably doesn't work too well, especially as they may change appearance (you might want to have PAC alternate between C and O, for example). Most likely the actual code will talk about these names and you'll have the in multiple places. Just use an enum to define the different items not defining any value for them and define their representation elsewhere:

enum Items { PAC, GHOST, FRUIT, POINTS, WALL, EMPTY, UNDEFINED };
extern char ItemDisplay[];

// elsewhere

char ItemDisplay[] = { 'C', '@', 'o', '.', '#', ' ', '+' };

... and then just use ItemDisplay[item] whenever you need to draw an item.

like image 92
Dietmar Kühl Avatar answered Feb 01 '26 21:02

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!