Question

I was just getting this error: "error: ‘Symbol’ does not name a type"

I found some other StackOverflow questions talking about circular dependencies, but that is not the case here. In fact I could reproduce it by putting this at the top of the source file:

class Symbol{int dummy;};
//class Symbol{int again;};
Symbol global_symbol;

This gives "error: ‘Symbol’ does not name a type" for the 3rd line. If I uncomment the 2nd line, I still get that same error, but just before it I now get: "error: redefinition of ‘class Symbol’" !!

After lots more poking around it appears a 3rd party library has an enum where Symbol is defined. Neither that library, nor my own code, uses namespaces, so as moving my code to be inside a namespace was already on my to-do list I'll do that next and hopefully the problem will go away.

But what confuses me is why I didn't get an error on the class Symbol{} line? If it clashes with an enum, to the extent that I would never be able to instantiate that class, why didn't it complain? I feel like I'm either missing a flag for g++, or there is a gap in my C++ knowledge. I'm bracing myself for someone to tell me this is a feature not a bug.

(BTW I am using g++ -c -std=gnu++0x -Wall -g -Werror ... and g++ 4.8.1)

Était-ce utile?

La solution

What you are seeing is a form of name hiding: a declaration of an variable or function Symbol will be found in preference to class Symbol ([basic.scope.hiding] §3.3.10/2). In the cases where C++ allows one declaration to hide another in the same scope, there is always an elaborated-type-specifier which still refers to the hidden declaration. They are so named because only a type (class or enum) may be hidden in this way; typedefs and templates cannot. The order of declaration is not significant.

In this case, you can use class Symbol to refer to the class when the variable or function is in scope:

class Symbol global_symbol;

Autres conseils

gcc error messages are not the most user friendly, due to the fact that C++ has quite a complicated syntax and the parser sometimes gets totally confused by the smallest error, such as a missing ;. For example, your code of the form

enum A{Symbol=0};

class Symbol{int dummy;};

int main() 
{
    Symbol global_symbol;
}   

where an enum having a Symbol is declared before the class Symbol gives me the following compiling error (I use g++4.8):

minimal.cpp: In function 'int main()':
minimal.cpp:13:9: error: expected ';' before 'global_symbol'
  Symbol global_symbol;
         ^
minimal.cpp:13:22: warning: statement has no effect [-Wunused-value]
  Symbol global_symbol;

So the best thing to do is to use namespaces in your code, or change the class name :) And you mentioned you used g++2.8. You meant 2.8 or 4.8? 2.8 is quite antique (16 years old), so it's not even fully C++98 compliant.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top