Jump to content
  • Advertisement
Sign in to follow this  
wally3182

Variable Access Question

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

I have a variable (say) x and I want every function in every (cpp) file to be able to access it. How do I do it? I hae tried putting it in a header file and including it in any of the cpp's where I will be using it, but I always get an error that goes like "x has already been declared in something.obj". I have tried putting it between #ifndef's and no luck there either. (edit) I have also tried using #pragma... I would also appreciate some sort of understanding on how to include files and so-on in the .net IDE. For example, consider the following files: stadfx.h and cpp mainfile.h and mainfile.cpp auxilaryfile.h and auxilaryfile.cpp Where do I include which ".h" file. Do I include them all in stdafx.h and include stdafx.h in all the cpp's???? coming back to my original question, in the above files, where would I declare x such that functions in both mainfile.cpp and auxilaryfile.cpp can access and modify it. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
If you need to do this, you should declare it as extern (e.g. extern int x;) in some header file, and in exactly one source file, define it (in the usual fashion). However, global variables are generally a bad thing; try, if you can, to find a better program design that does not require it.

Share this post


Link to post
Share on other sites
Quote:
Original post by Miserable
If you need to do this, you should declare it as extern (e.g. extern int x;) in some header file, and in exactly one source file, define it (in the usual fashion). However, global variables are generally a bad thing; try, if you can, to find a better program design that does not require it.


Don't declare the variable(s) as extern in the source file though. Also, in the header file where they are declared as extern, you can wrap your globals in a

namespace nMyGlobals
{
}

to avoid possible name clashes. They can then be accessed as nMyGloabals::variableName. That's my style, at least. Like Miserable said, you should try to avoid using globals wherever possible.

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!