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 Overflow
Top answer
1 of 4
35

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.

2 of 4
16

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;
Discussions

Global Objects - C++ Forum
Im making a game engine right now and i need to make an object called "engine" from the Engine class available to all the other classes i made in other source files. How would i go about making a "global object"? I know that variables have to be declared as: header file 1: extern int a; source ... More on cplusplus.com
🌐 cplusplus.com
C++ code and risk of global objects
Browsing the forum I saw a topic related to: "when I place my global object outside setup() or loop() - it does not work" (or I see the read morsing LED for a hard crash, aka memory violation). Here my thoughts: C++ is really nice. But on embedded platforms it can be tricky. More on forum.arduino.cc
🌐 forum.arduino.cc
0
0
May 12, 2022
How to create a global object/instance o - C++ Forum
If you want a different name for each one instead of a different number, try std::map. But this sounds like you're trying to replicate global variables and in a bad way. Can you be more precise about what you're trying to do? ... I want to programm where every object is ... More on cplusplus.com
🌐 cplusplus.com
Initialize Global object Later Question
I think I understand how to use object pointers, I used this example: https://forum.arduino.cc/t/initializing-global-object-lcd-from-setup/310096 Here is one I wrote up: class MyClass { public: MyClass(uint32_t Baud) { Serial.begin(Baud); Serial.println("Serial Started"); X = 0; } void Print() ... More on forum.arduino.cc
🌐 forum.arduino.cc
1
0
April 3, 2022
🌐
Reddit
reddit.com › r/embedded › best practice for globals in c++
r/embedded on Reddit: Best Practice for globals in C++
April 30, 2024 -

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:

  1. Pass in a reference of the global object in the logging class constructor so I have a reference at all times to use.

  2. create a globals file to define global objects and include this in each interface that needs to access them.

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

🌐
Cplusplus
cplusplus.com › forum › general › 47139
Global Objects - C++ Forum
If you define an object in global scope then it is available to the whole application. You simply need to declare its existence before you use it by including its header file. Header: ... Hi, I believe if you want to make members of objects of type Engine to be shared by all objects of type ...
🌐
MIT
web.mit.edu › tibbetts › Public › inside-c › www › initializing-globals.html
The Secret Life of C++: Initializing Globals
Basically, global constructors and destructors get "registered" and called at program start and shutdown, using the _init and _fini sections of the executable.
🌐
GitHub
gist.github.com › 3000412
Global Variables in Objective-C (Singleton) · GitHub
Global Variables in Objective-C (Singleton). GitHub Gist: instantly share code, notes, and snippets.
🌐
emmtrix Wiki
emmtrix.com › wiki › Demystifying_C++_-_Initialization_of_Global_Variables
Demystifying C++ - Global Variable Initialization in C vs. C++
September 4, 2024 - In contrast, C++ allows for more flexible initialization. When global objects or variables in C++ are created that require non-constant initialization or have a constructor, the compiler generates a special initialization function (often referred to as "global constructor").
Find elsewhere
🌐
Arduino Forum
forum.arduino.cc › official hardware › portenta family › portenta h7
C++ code and risk of global objects - Portenta H7 - Arduino Forum
May 12, 2022 - Browsing the forum I saw a topic related to: "when I place my global object outside setup() or loop() - it does not work" (or I see the read morsing LED for a hard crash, aka memory violation). Here my thoughts: C++ is…
🌐
Cplusplus
cplusplus.com › forum › general › 109265
How to create a global object/instance o - C++ Forum
If you want a different name for each one instead of a different number, try std::map<std::string, MyClass>. But this sounds like you're trying to replicate global variables and in a bad way. Can you be more precise about what you're trying to do? ... I want to programm where every object is ...
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Initialize Global object Later Question - Programming - Arduino Forum
April 3, 2022 - I think I understand how to use object pointers, I used this example: https://forum.arduino.cc/t/initializing-global-object-lcd-from-setup/310096 Here is one I wrote up: class MyClass { public: MyClass(uint32_t Baud) { Serial.begin(Baud); Serial.println("Serial Started"); X = 0; } void Print() { Serial.print("Print msg #"); Serial.println(X); X++; } private: uint32_t X; }; MyClass * Obj; void setup() { Obj = new MyClass(115200); }...
🌐
Microsoft
devblogs.microsoft.com › dev blogs › the old new thing › when are global objects constructed and destructed by visual c++?
When are global objects constructed and destructed by Visual C++? - The Old New Thing
October 17, 2014 - Today we’re going to fill in the following chart: When does it run? Constructor Destructor Global object in EXE Global object in DLL The C++ language specification provides some leeway to implementations on when global static objects are constructed. It can construct the object before main begins, or it construct the object on demand according […]
🌐
Quora
quora.com › Why-dont-we-store-objects-in-global-scope-instead-of-the-heap-in-C-C++-if-we-want-the-object-lives-outside-stack
Why don't we store objects in global scope instead of the heap in C/C++ if we want the object lives outside stack? - Quora
Answer (1 of 5): You can do it. Objects will go on the heap only if allocated using “new”. But be aware that it’s bad practice and there are many issues related to it. Globals are generally bad because they are accessed without going through function interfaces.
🌐
Quora
quora.com › Can-I-declare-NSString-type-objects-as-global-variable-in-Objective-C
Can I declare NSString type objects as global variable in Objective-C? - Quora
Answer (1 of 2): Certainly you can. In fact I recommend you to make then constant string as [code]NSString* const myString = @"MyString"; [/code]If you want to access this in multiple files, you need to define this in .m file and declare this variable as extern in .h file. Else you will get link...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › global-variables-in-c
Global Variables in C - GeeksforGeeks
Global variables have a program-wide scope which means can be accessed and modified by any function in the program.
Published   2 weeks ago
Top answer
1 of 5
6

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.

2 of 5
2

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.

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 2154470 › in-c-are-global-objects-guaranteed-to-exist-throug
In C++, are global objects guaranteed to exist throughout the execution of a SetConsoleCtrlHandler() callback function? - Microsoft Q&A
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. ... It would be helpful if we knew what console signals were being handled and how they relate to a global object.