tags:

views:

58

answers:

1

I got an error: redeclaration of enumerator message when I compile my codes, please kindly see the code below from my foo.h header file,

//foo.h

struct FG
{
   enum
   {
      black = 1,
      red   = 2,
      green = 3
   };
};

struct BG
{
   enum
   {
      black = 1,
      red   = 2,
      green = 3
   };
};

My question is, why I am getting the enumerator redeclaration? my enums are in the different structs, so I can use the following,

BG::black
FB::black

Please advise.

EDIT: here is the exact error

/home/sasayins/foobar/foo.h:10: error: redeclaration of enumerator ‘black’
/home/sasayins/foobar/foo.h:3: note: previous definition of ‘black’ was here
+3  A: 

As noted in the comments, if you are using a C compiler instead of a C++ compiler to compile the code, then you will inevitably get the errors shown. The code is only valid in C++, so you must use a C++ compiler to compile it.

Further, if you are using a C compiler, you would not be able to use the qualified names like 'FG::black' or 'BG::black' to disambiguate the names; C does not recognize double-colon as a valid symbol.


From the comments below:

Actually the problem is in another file; my C file includes the header file, which is the header contains a C++ code file, so that is the cause of the problem. So my header file (foo.h) contains a valid code. Could you suggest a structure for C header file?

If you need your header foo.h to be bilingual in C and C++, you will probably do best with a single enumeration, losing the need for the 'FG::black' and 'BG::black' qualifiers altogether:

#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

typedef enum Colour
{
    black = 1,
    red   = 2,
    green = 3
} Colour;

typedef struct FG
{
    ...
    Colour  shade;
    ...
} FG;

typedef struct BG
{
    ...
    Colour  shade;
    ...
} BG;

#endif // FOO_H_INCLUDED

Note that the typedefs are needed to allow C code to refer to 'BG', 'FG' and 'Colour' without a prefix 'struct' or 'enum'; pure C++ would not need those typedefs at all. However, you are writing bilingual code and occasionally you have to write in a way that seems slightly stilted in one or the other language.

Jonathan Leffler
thanks, it seems I am having a problem in my makefile.
sasayins
@sasayins: then maybe you should show the makefile? Or the compilation command? What is the extension on your C++ source file? Using .cpp or .cxx or .C is conventional, but the latter (.C) could be confused with .c on a case-insensitive file system.
Jonathan Leffler
@Jonathan Leffler: Thanks a lot. Actually the problem is in another file, my C file includes the header file, which is the header contains a C++ code file, so that is the cause of the problem. So my header file(foo.h) contains a valid code. Could you suggest a structure for C header file? thanks
sasayins
That is great. Thanks!
sasayins