Sign in to follow this  

C++ static member linker problem

Recommended Posts

Hi all, I'm having trouble with the following: foo.h
#ifndef FOO_H
#define FOO_H

#include <string>

class Foo {
  typedef std::string StringType;

  // ...

  static const StringType default;
  // ...


#include "foo.h"

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

#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.

Share this post

Link to post
Share on other sites
Original post by ToohrVyk
Is foo.cpp compiled and linked with the rest of the program?


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

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.

Original post by bakery2k1
You want:

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

Thanks. That's exactly what I needed.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this