Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a global variable that could be used in the entire program

Tags:

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish this in C++?

Thanks.

like image 771
trrrrrrm Avatar asked Jan 08 '10 17:01

trrrrrrm


People also ask

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you use global variables in programming?

Use of the Global Variable in CThe global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.

How do you declare a global variable in C++?

In C++, variables can also be declared outside of a function. Such variables are called global variables. By convention, many developers prefix global variable identifiers with “g” or “g_” to indicate that they are global.

How do you declare a global variable in Java?

To define a Global variable in java, the keyword static is used. Java actually doesn't have the concept of Global variable, it is known as class variable ( static field ). These are the variables that can be used by the entire class. // constructer used to initialise a Student object.


2 Answers

global.h extern int myVar;  global.cpp #include "global.h" int myVar = 0;  // initialize  class1.cpp #include "global.h" ...  class2.cpp #include "global.h" ...  class3.cpp #include "global.h" ... 

MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initialize myVar in any of the class .cpp's but I think this is cleaner for larger programs.

like image 166
fupsduck Avatar answered Sep 18 '22 15:09

fupsduck


While I would like to avoid global variables like the plague as our software cannot be multithreaded effectively due to the high reliance on global variables, I do have some suggestions:

Use a Singleton. It will allow you to keep the code and access clean. Part of the problem with a global variable is you don't know what code has modified it. You could set the value of global somewhere in your function relying on the hope that no one else will change it, but function your code calls, fooA, changes it and now your code is a) broken, and b) hard to debug.

If you have to use a global variable without touching the singleton pattern, look at fupsduck's response.

like image 32
Lyndsey Ferguson Avatar answered Sep 22 '22 15:09

Lyndsey Ferguson