Jump to content
  • Advertisement
Sign in to follow this  
tasen

C++ static member linker problem

This topic is 3789 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!