Traditionally, global variables are declared in a header, and defined in a source file. Other source files only need to know how it is declared to use it (i.e. its type and its name). As long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.
Somewhere in your header, you would declare a global variable like this:
extern int GlobalInt;
The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists. It may be defined later or it may not (it is not the compiler's responsibility to ensure it exists, that is the linker's job). It is similar to a function prototype in this regard.
In one of your source files, you define the GlobalInt integer:
int GlobalInt = 4;
Now, each file that includes the header will have access to GlobalInt, because the header says it exists, so the compiler is happy, and the linker will see it in one of your source files, so it too will be happy. Just don't define it twice!
However
You should consider whether or not this approach is useful. Global variables get messy for a number of reasons (trying to find out exactly where it is defined or declared, threading issues), there is usually not a need for global variables. You should perhaps consider using a singleton approach.
Answer from dreamlax on Stack OverflowTraditionally, global variables are declared in a header, and defined in a source file. Other source files only need to know how it is declared to use it (i.e. its type and its name). As long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.
Somewhere in your header, you would declare a global variable like this:
extern int GlobalInt;
The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists. It may be defined later or it may not (it is not the compiler's responsibility to ensure it exists, that is the linker's job). It is similar to a function prototype in this regard.
In one of your source files, you define the GlobalInt integer:
int GlobalInt = 4;
Now, each file that includes the header will have access to GlobalInt, because the header says it exists, so the compiler is happy, and the linker will see it in one of your source files, so it too will be happy. Just don't define it twice!
However
You should consider whether or not this approach is useful. Global variables get messy for a number of reasons (trying to find out exactly where it is defined or declared, threading issues), there is usually not a need for global variables. You should perhaps consider using a singleton approach.
Don't. Global variables are often a sign of poor design. A common replacement in Objective-C is a class method that returns an object (that may or may not be a singleton), such as [NSUserDefaults standardUserDefaults] or [UIDevice currentDevice].
However, if you must use a global variable, read on.
In your header:
extern NSString *someString;
extern NSInteger someInteger;
In your implementation file:
NSString *someString = @"DEFAULT_VALUE";
NSInteger someInteger = DEFAULT_VALUE;
Global Objects - C++ Forum
C++ code and risk of global objects
How to create a global object/instance o - C++ Forum
Initialize Global object Later Question
Videos
Exclusively use C at work and am working on a C++ project to teach myself some of the basics and was running into an issue with how I should setup global objects. I have a logging class for creating asserts which ideally would be included in all modules, however I'm not sure the best way to go about this.
As an example, if i were using C I would setup my loggging interface as such:
log.h
void init_log(); //sets some static variables void add_log();
example.c
#include "log.h"
void example_function(void)
{
add_log();
}main.c
#include "log.h"
#include "example.h"
int main()
{
init_log();
while( true )
{
example_function();
}
}However I can't do this pattern in C++ because the object itself holds the init variables. My thoughts to implement a C++ solution are:
Pass in a reference of the global object in the logging class constructor so I have a reference at all times to use.
create a globals file to define global objects and include this in each interface that needs to access them.
make globals a singleton class, so i can access it that way.
Any suggestions for the best way to go about this would be appreciated!
Try to declare the variable globally (outside of the function) use the function to change the global variable.
Variables declared inside of a function are only accessible in that function; they are called local variables as they are local to the function in which they are declared.
The main() function cannot access the local variables of another function.
Globally declared variables are visible everywhere.
After the function is called, your array no longer exists:
void makeExampleStruct ()
{
exampleStruct exampleObj[30];
// exampleObj is created here
for (int r=0;r<=30;r++)
{
exampleObj[r].ID=r;
}
// exampleObj is destroyed here.
}
So even if you could access the object, it would be illegal to do so after the function returns, since the object's lifetime has ended.
Yes, you can declare a global variable of any type, class or not.
No, you can't then "call" the constructor again inside a function to initialize it. You can however use the copy assignment operator to do it:
Foo foo;
int main()
{
foo = Foo(1, 3);
}
Or you can have a "setter" function that is used to set or reinitialize the object.
By the way, and depending on the data in the class, you might want to read about the rule of three.
It's certainly possible to have global objects. The correct way in your case is:
Foo foo(1, 3);
int main()
{
// ...
}
So, you have to decide between a singleton and a bunch of free functions in a namespace, with some dedicated global state either way?
First, why do you want a singleton?
If it is just to ensure they share the state, consider extracting it into namespace-level TU-internal variables, and make any functions you want static. No need to muck around with singletons, which are ill regarded due to blatant over- and mis-use, aside from mis-implementation.
Next, why a class at all?
This is not Java, you can have free functions and global state outside classes, perfectly hidden from the outside unless external linkage is requested. It has the advantage of easier extensibility, and unless you need to provide a specific interface (for static injection with templates or dynamic injection with inheritance), there is no downside.
This is actually the preferred way, absent reason to do otherwise.
Assumed the free functions which belong to the same component have their own namespace, this is just a matter of taste. I am sure you won't find a hard, technical argument for or against those two approaches, they will both work and don't provide a huge difference in readability or maintainability.
So I would recommend you choose the variant which fits best to the programming style or "school of thought" of the overall system. If you prefer OO programming, use a class + single object. If you prefer hybrid style, or to use as few C++ language elements as required, use free functions. And if you don't have any preference, flip a coin.