Linker Error: Unresolved external symbol

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AceKnocks
    New Member
    • Jan 2008
    • 14

    #1

    Linker Error: Unresolved external symbol

    Hi all,
    I have these two classes with following structure

    Code:
    //main.cpp
    
    class Tree {
    public:
    static bool flag;
    Tree() { 
    flag = true;
    }
    };
    
    class b {
    public:
    static bool isValid();
    };
    
    static isValid() {
    if (Tree::flag) ... some code
    }
    When compiling the above code, there were no errors. However, upon linking I get the following error
    error LNK2001: unresolved external symbol "public: static bool Tree::flag" (?flag@Tree@@2_ NA)
    fatal error LNK1120: 1 unresolved externals

    What am I doing wrong here?
  • AceKnocks
    New Member
    • Jan 2008
    • 14

    #2
    Just got to know that if we need to access a static data member from a class within a file scope, we need to define it after class declaration.

    http://msdn2.microsoft .com/en-us/library/b1b5y48f(VS.80) .aspx

    Resolved! :)

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      That's because the static variable is not part of any object. Therefore, when is it created?? The answer is that you need to create it yourself as a static variable.

      That said, why is the variable static in the first place. On sht surface this does ot appear to be a situation where a static variable should be used.

      I try to avoid static variables due to problems you get into with multi-threaded programs where more than one thread can access the sam variable. I see static anything as warning that bad code follows.

      Comment

      • AceKnocks
        New Member
        • Jan 2008
        • 14

        #4
        Yep, I do agree on that but here I class B has to count instances of the class A's objects created at any given point in time.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Originally posted by AceKnocks
          Yep, I do agree on that but here I class B has to count instances of the class A's objects created at any given point in time.
          Check out the Observer design pattern.

          You don't need a static variable to do this.

          However, if you use one, you have to create it manually.

          Comment

          Working...