C++ static member linker problem

Started by
5 comments, last by tasen 16 years, 2 months ago
Hi all, I'm having trouble with the following: foo.h
#ifndef FOO_H
#define FOO_H

#include <string>

class Foo {
public:
  typedef std::string StringType;

  // ...

  static const StringType default;
private:
  // ...
};

#endif


foo.cpp
#include "foo.h"

const Foo::StringType default = Foo::StringType();


main.cpp
#include "foo.h"

int main()
{
  Foo::StringType s = "foo";

  if (s == Foo::default)
    s = "bar";
}


Trying to compile this (on MSVC++ 2008 Express) gives the following linker errors: 1>main.obj : error LNK2001: unresolved external symbol "public: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const Foo::default" (?st@Foo@@2V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@B) 1>C:\Documents and Settings\d\Desktop\foo\Debug\foo.exe : fatal error LNK1120: 1 unresolved externals I can't seem to figure out what the problem is; if anyone can help me out I'd greatly appreciate it.
Advertisement
Is foo.cpp compiled and linked with the rest of the program?
How on earth does that compile? Using a keyword as a variable name should blow up in half a dozen ways before it even hits the link stage.
Visual C++ 2005 seems to only treat "default" as a keyword if it's followed by a colon, even with the language extensions disabled. Apparently, so does the 2008 version.
Quote:
const Foo::StringType default = Foo::StringType();


You want:
const Foo::StringType Foo::default = Foo::StringType();
Isn't "default" a reserved word that you cant use?
__________________________________________
Eugene Alfonso
GTP | Twitter | SFML | OS-Dev
Quote:Original post by ToohrVyk
Is foo.cpp compiled and linked with the rest of the program?


Yes.

Quote:Original post by SiCrane
How on earth does that compile? Using a keyword as a variable name should blow up in half a dozen ways before it even hits the link stage.


Sorry, that wasn't actually what the variable was called in my program, I changed it to try and make the example a bit more clear (forgetting that it actually is a keyword!). However, just for fun I changed it to default and strangely enough it compiles. o_O

Quote:Original post by ToohrVyk
Visual C++ 2005 seems to only treat "default" as a keyword if it's followed by a colon, even with the language extensions disabled. Apparently, so does the 2008 version.


That's correct.

Quote:Original post by bakery2k1
You want:

const Foo::StringType Foo::default = Foo::StringType();


Thanks. That's exactly what I needed.

This topic is closed to new replies.

Advertisement