Sign in to follow this  
Flopid

Program Wide Global Vars in C++?

Recommended Posts

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

Share this post


Link to post
Share on other sites

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 )

Share this post


Link to post
Share on other sites

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!!!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

[quote name='Flopid' timestamp='1356749322' post='5015285']
It may be breaking the laws of OOP but I was just wondering if it was possible in C++.
[/quote]

 

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! ;)

Share this post


Link to post
Share on other sites

[quote name='Misery' timestamp='1356782306' post='5015404']
Please see info about singleton pattern. It is considered an alternative to global variables.
[/quote]

 

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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).

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

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 : )

Share this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

I am starting to think that the use of globals is not evil in itself. It is a problem of scale and scope. To take an example, which is unrealistic but possible:

 

Take a C program "PROG" where every heap allocated variable is globally defined. This kind of application is the way programming was done in the old days, before object orientation and ADT was invented (please allow me the simplification). This PROG will be hard to maintain and inflexible when it grows. If the complete source code fits into one screen, it should still be fine. However, as many found out, when PROG grows there is point when maintenance gets unreasonable. It simply takes too much effort to do changes, with severe side effects making it hard to guarantee correctness.

 

If this big PROG is packaged into one single huge class in C++, it will fulfill the requirement of not using globals. But the basic problem still remains, which is a problem of scale. Parameters in a class can be just as problematic as global parameters, if the class is too big (bloated, fat class, ...).

 

From that point of view, stating that global variables are evil is a simplification? The real problem is the size of the scope where a variable (or function and sometimes type!) is available. But I suppose it is much easier to explain "Don't use global variables", than to explain that scopes shall be kept to a minimum size.

Share this post


Link to post
Share on other sites
I try to design without globals in mind, but things like debugger/profiler that I have to use and I _need_ access to it from basically every part of my code to dump something on the screen or profile execution just require some kind of global var / singleton (which I don't like and prefer just typical global variable). I tried hard to figure how to pass it around and having it passed through all object chains because I may need it at some point is just plain stupid IMO.

Instead I just create a global instance of Debugger class and in any .cpp file that I need access to it to dump some data or profile part of the code, I use extern. I really can't see how this can be done better - I can't use global functions because I need a state (debug drawing requires geometry to be compiled and drawn each frame etc, so instead of one class I'd have to get some global variables anyway and it will be ugly). Its also only for debugging, so in release mode my code is global free anyway.

I think people who are 100% against globals are some hard to convince OO-freaks. Edited by noizex

Share this post


Link to post
Share on other sites
Take a C program "PROG" where every heap allocated variable is globally defined. This kind of application is the way programming was done in the old days, before object orientation and ADT was invented (please allow me the simplification). This PROG will be hard to maintain and inflexible when it grows. If the complete source code fits into one screen, it should still be fine. However, as many found out, when PROG grows there is point when maintenance gets unreasonable. It simply takes too much effort to do changes, with severe side effects making it hard to guarantee correctness.

Very true. It's important to know why things can be problematic rather than just that they can be problematic. This frees people to make more enlightened decisions about design because they learn the underlying problem (and how to fix it) rather than just the rule. Edited by Khatharr

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this