Jump to content

  • Log In with Google      Sign In   
  • Create Account


Program Wide Global Vars in C++?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
22 replies to this topic

#1 Flopid   Members   -  Reputation: 122

Like
0Likes
Like

Posted 28 December 2012 - 08:48 PM

I've just recently learned from my program that "static" or pointer variables do not neccesseraly mean global program wide. I have a single .h file included for main .cpp and another .cpp file. When I changed the variable in main and read it in the other class it was not the same value as I've set it in the main class, even though it was declared static, or as I've tested even if it is a pointer, in the .h file.

 

Seems like the only way in C++ to have access to a variable you would like to use in another class is to pass it through a function or a constructor as well as using inheritance. As I recall in Java or C# a static variable or a function can be defined in one class and changed from a class while changing it for all the other classes.

 

It may be breaking the laws of OOP but I was just wondering if it was possible in C++.

 

Thank you, and have a nice day!!! smile.png



Sponsor:

#2 Rod Ochoa   Members   -  Reputation: 123

Like
3Likes
Like

Posted 28 December 2012 - 09:22 PM

global.hpp

 

extern int counter;

 

global.cpp

 

include "global.hpp"

int counter;

 

other.cpp

 

include "global.hpp"

 

// Use counter.......


Edited by Rod Ochoa, 28 December 2012 - 09:23 PM.


#3 LordJulian   Members   -  Reputation: 151

Like
2Likes
Like

Posted 28 December 2012 - 10:06 PM

And, taking the wonderful example of Rod, if you don't feel like including a whole h(pp) file for a variable, you can extern declare said variable in any place that you want it.

 

i.e.

 

void BlaBluBli()

{

 int a = 2;

extern int counter = a + 7;

}

 

As long as you ONLY declare it NON EXTERN once, every other external declaration will be solved by the compiler at link time.

 

But, DON'T! NEVER! Not even once! As an abuser of global variables, especially at work, especially when I need to do things quickly, I can tell you that usually it comes back to byte you (pun intended!).  The hassle, when you decide to expand on your work, far outweighs any gains; usually this is a sign that your overall design has a few flaws in it.

 

Don't do it, EVER, I mean it :P  (or if you do, don't let anyone else play with your globals :P )



#4 Flopid   Members   -  Reputation: 122

Like
0Likes
Like

Posted 28 December 2012 - 11:54 PM

Ah lol the extern, completely forgot it existed. I'll take your advice, but I like to make a mess also though, makes me look like I've been working : )

 

Thank you very much!!!



#5 Misery   Members   -  Reputation: 305

Like
0Likes
Like

Posted 29 December 2012 - 05:58 AM

It may be breaking the laws of OOP but I was just wondering if it was possible in C++.

 

I don't feel like it is breaking the laws of OOP. It depends on what you need. Sometimes it is used as it is the most convienient approach. Please see info about singleton pattern. It is considered an alternative to global variables.



#6 Rattenhirn   Crossbones+   -  Reputation: 1664

Like
2Likes
Like

Posted 29 December 2012 - 07:14 AM

It may be breaking the laws of OOP but I was just wondering if it was possible in C++.

 

C++ is a multi paradigm language, so it allows you to follow the "laws" of OOP, as well as a lot of other programming styles.

 

For values that have to be stored globally, using a global variable is a pretty good idea! ;)



#7 larspensjo   Members   -  Reputation: 1526

Like
2Likes
Like

Posted 29 December 2012 - 09:05 AM

Please see info about singleton pattern. It is considered an alternative to global variables.

 

Actually, the singleton pattern is sometimes misused as an alternative to global variables. In C++, types declared in header files have global scope. The purpose of the singleton pattern is to prevent a type from being instantiated more than once. This restriction should only be used if the type will stop working, not because the intent is to only instantiate one. However, it is usually better to design the type in such a way that it will allow multiple instances.

 

I hope I don't start a flame war here, please search on Google for multiple explanations why the singleton pattern shouldn't be used.


Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#8 Cornstalks   Crossbones+   -  Reputation: 6966

Like
4Likes
Like

Posted 29 December 2012 - 10:18 AM

Please see info about singleton pattern. It is considered an alternative to global variables.

Nooooo! The singleton pattern and global variables solve two different problems, and the people who use a singleton when all they really wanted was a global variable are likely just trying to horribly abuse objected oriented programming, claiming that because the global is wrapped up in a singleton class it's somehow "better," which is just plain wrong, wrong, wrong.

 

If you need a global, use a global. If you need a singleton, use a singleton. They are not equivalent alternatives. Yes, a singleton is, you could probably argue, a form of a global variable, but it's got extra baggage that globals don't. The reason people use singletons (or at least the reason they should use singletons) over globals is because they specifically wantneed that extra baggage. If you really have no need for that extra baggage, using a singleton is simply using the wrong tool for the job.

 

Now, people will argue whether or not you should use singletons and/or globals at all, and I'm not going to turn this into a debate over if one should never use them or not, but I will say that you should always try to minimize their usage. Passing things as parameters instead of using globals is easier to debug, easier to make your code thread safe and multithreaded, easier to follow the program flow and design, etc. so at the very least, try to minimize their usage. It's easy to make everything a global, but having a ton of globals will quickly turn your code into a spaghetti mess.


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#9 Khatharr   Crossbones+   -  Reputation: 2828

Like
0Likes
Like

Posted 29 December 2012 - 10:34 AM

I think most of our denizens are in agreement about the use of singleton... Even if everyone will argue about why they're in agreement.

 

lol


void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#10 LordJulian   Members   -  Reputation: 151

Like
0Likes
Like

Posted 29 December 2012 - 05:16 PM

I actually am not very found of singletons; they can, as stated before, be easily abused to take a different role than they were designed. And, again, not a fan about "the role that they were designed for". You NEED one instance, I'm gonna trust that you are a big enough boy to instantiate it only once. You cannot? Oh, I have news for you... you're doing something wrong :) <insert rage replies here>

 

Also, I've met, more than once, naïve singleton implementation that did more wrong than right; for example in the function I wrote I needed to make sure that the said singleton was "destroyed" (the why's of me needing that are a whole different STUPID story, needles to say, I needed to), and simply checking if the "singleton" instance was != NULL would have the "nice" side effect of instantiating it if it was not instantiated before... WHICH WAS STUPID, error inducing and simply nerve wreaking. Me having to check the implementation of something that advertises itself as a singleton and modify it is not my idea of a fun time :)

 

Usually, through careful architecture design, no singleton would be implemented... ever... nor global variables. But, sure, as with everything else in C++, you want it, you could usually build/use it; but you usually pay the appropriate price for it



#11 Amr0   Members   -  Reputation: 1033

Like
1Likes
Like

Posted 30 December 2012 - 03:12 AM

Somewhat relevant: Unifying Global Variable Declarations & Definitions Using The Preprocessor. It's an old trick which can be useful as the list of global variables grows, but of course, if you have a long list of global variables, it's a sign that your design could use cleaning up.


Edited by Amr0, 07 February 2014 - 01:10 PM.


#12 NewDisplayName   Members   -  Reputation: 351

Like
0Likes
Like

Posted 31 December 2012 - 02:44 AM

Personally, as a thumb rule, I avoid using globals altogether. Globals can ruin many a days in debugging some bizarre issue, apart from other evils.

And using Singleton for global should also be the absolute last resort. Good design can very well just use the reference to one object across different classes. And that almost always addresses the problem of globals.

Only good example I can think of when to use globals is if you want to include some generic information in minidumps.



#13 Codarki   Members   -  Reputation: 462

Like
0Likes
Like

Posted 31 December 2012 - 10:17 AM

The OP is specifically talking about singletons. The title is just misleading. The suggestion to use singletons is void. The singleton has many ways lagging a project weeks behind. I remember one time when we had a templated singleton, that is static data member in header file. The result was that we had 2 different singletons in different translation units. This was the at the same time we we're battling about the construction and destruction order. Funny thing about destruction is, that if singleton object being destructed (after main() returns) refers to another singleton, and that singleton have already been destructed, the access function (class.instance() or such) recreates it. It's destructor is not gonna be called again.

 

My suggestion is to wrap the global parameter you want to RAII object, and while it's alive, global access is possible. Any access outside of the scope guarded object should throw exception or cause abort(). This way you can manage the lifetimes of everything, and any access to non-living objects are caught at development time.

 

I can give example of my suggestion if you need one (or other members here).



#14 Cornstalks   Crossbones+   -  Reputation: 6966

Like
0Likes
Like

Posted 31 December 2012 - 12:07 PM

The OP is specifically talking about singletons.

No (s)he isn't. Flopid just talks about having static/shared (i.e. global) variables in the original post, but there is nothing that sounds at all like a singleton.

 

@Flopid: I'm not sure how you were using the static keyword, but it has different effects depending on where you use it. I wrote a little post on my blog about it which might explain things for you a bit. It's hard to give you a more specific response, seeing as I'm not sure how you were using static, but this might clear some things up. It's possible you were making a static global variable, which would indeed mean that each source file gets its own copy of this global variable, and changes made from one file are not reflected in others.


Edited by Cornstalks, 31 December 2012 - 12:09 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#15 Flopid   Members   -  Reputation: 122

Like
0Likes
Like

Posted 02 January 2013 - 03:49 PM

Wow a lot of info from all of the posts, just for a global variable. I am not completely sure how to implement a singleton yet, but I found this website. There are a few questions I have about this, but it is probably a subject for another thread. It seems as if a singleton is much better to use in a team environment, where people can accidentaly instantiate a global more than once, plus as I see it is more safe for threads. I'll have to reasearch more, but for now I'll probably just use "extern" as I can keep track of the code I have.

 

This bump is not intentional, just wanted to contribute to the conversation : )



#16 Khatharr   Crossbones+   -  Reputation: 2828

Like
1Likes
Like

Posted 02 January 2013 - 06:31 PM

I'd recommend reading those 'why singletons are evil' articles before you joyously leap into using them everywhere. There's some really good points made.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#17 Cornstalks   Crossbones+   -  Reputation: 6966

Like
1Likes
Like

Posted 02 January 2013 - 07:57 PM

It seems as if a singleton is much better to use in a team environment, where people can accidentaly instantiate a global more than once

If you have that many global variables, I'd say you have a problem. Even worse, it sounds like they're scattered all over the place. Using singletons in this case sounds more like putting duct-tape over a bullet wound instead of doing surgery, removing the bullet, and putting proper bandaging on.

 

plus as I see it is more safe for threads.

They're not. At all. There is nothing about a singleton that makes it more threadsafe than a global. Any thread safety you add to a singleton you must also add to a global. In fact, singletons may be even less safe (because they prevent another instance from being created and used).

 

This bump is not intentional, just wanted to contribute to the conversation : )

It's always good to come back and respond to threads :)


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#18 Khatharr   Crossbones+   -  Reputation: 2828

Like
2Likes
Like

Posted 02 January 2013 - 08:05 PM

Using singletons in this case sounds more like putting duct-tape over a bullet wound instead of doing surgery, removing the bullet, and putting proper bandaging on.
wait_wut.jpg
Been there.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#19 Flopid   Members   -  Reputation: 122

Like
0Likes
Like

Posted 03 January 2013 - 12:00 AM

I usually do try to follow OOP without globals, but it seems when, for example, you have a variable that you have passed through a function or a constructor to many classes you pretty much have to somehow document it anyway, for code clarity. In this case it would seem like a global would be just a bit easier to manage. That, however, raises a question, why did you bite the bullet, and thus leaves the scope of this book.



#20 Cornstalks   Crossbones+   -  Reputation: 6966

Like
0Likes
Like

Posted 03 January 2013 - 12:19 AM

I usually do try to follow OOP without globals, but it seems when, for example, you have a variable that you have passed through a function or a constructor to many classes you pretty much have to somehow document it anyway, for code clarity.

For what it's worth, passing parameters is more "self-documenting" than a global is. But if you find yourself sharing the same object in many classes, your classes probably aren't design correctly and following SRP.

 

But yeah, whether or not you should use globals and what alternatives there are to globals is a different topic which has been discussed many times. Getting into that huge mess wouldn't be very relevant to this thread's focus.


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS