By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,496 Members | 1,527 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,496 IT Pros & Developers. It's quick & easy.

Linker Error: Unresolved external symbol

P: 14
Hi all,
I have these two classes with following structure

Expand|Select|Wrap|Line Numbers
  1. //main.cpp
  2.  
  3. class Tree {
  4. public:
  5. static bool flag;
  6. Tree() { 
  7. flag = true;
  8. }
  9. };
  10.  
  11. class b {
  12. public:
  13. static bool isValid();
  14. };
  15.  
  16. static isValid() {
  17. if (Tree::flag) ... some code
  18. }
  19.  
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?
Jan 5 '08 #1
Share this Question
Share on Google+
4 Replies


P: 14
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! :)
Jan 5 '08 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
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.
Jan 6 '08 #3

P: 14
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.
Jan 6 '08 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
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.
Jan 7 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.