Jump to content
  • Advertisement
Sign in to follow this  
TiitHns

cant figure out global var problem

This topic is 3832 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

file1.h #ifndef FILE1_H #define FILE1_H class myclass { }; extern myclass *p; #endif file1.cpp #include "file1.h" //define class myclass:: ... file2.h #ifndef FILE2_H #define FILE2_H #include "file1.h" myclass *p = 0; //some functions #endif file2.cpp #include "file2.h" //define functions use global p This way error LNK 2005 occurs, if i delete file2.cpp LNK 2005 error gone. How to avoid this multiple def. without deleting file2.cpp

Share this post


Link to post
Share on other sites
Advertisement
A global variable should be defined in a single translation unit, which will be easiest to achieve by defining it in one of your source files.
As it is now, it's defined in all translation units that include file2.h.

Share this post


Link to post
Share on other sites
in file2.h replace "myclass *p = 0;" by "extern myclass *p;", and in file2.cpp, add "myclass *p = 0;"

What you're doing now is like creating "p" in every .cpp file where file2.h in #included, which the linker will not permit.

Also, I've seen this mistake "fixed" by adding "static" in front of the declaration in the header file. It may stfu the compiler but then you will end up with a very strange behavior. Try to understand why ;)

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!