You probably really do not want to do this, but if you must - in the file that contains main:
#include "A.h"
A a;
int main() {
...
}
and then in the files that need to access the global:
#include "A.h"
extern A a;
You will need to put the declaration of A in the A.h header file in order for this to work.
Answer from anon on Stack OverflowYou probably really do not want to do this, but if you must - in the file that contains main:
#include "A.h"
A a;
int main() {
...
}
and then in the files that need to access the global:
#include "A.h"
extern A a;
You will need to put the declaration of A in the A.h header file in order for this to work.
In C++ declaring a global instance of a class is a no-no.
You should instead use the singleton pattern, which gives you a single instance of your object accessible from the entire application.
You can find a lot of literature on C++ singleton implementation, but wikipedia is a good place to start.
Thread safe singleton pattern implementation has already been discussed on stackoverflow.
singleton - Global instance of a class in C++ - Stack Overflow
Can I declare class object globally in c++? - Stack Overflow
Declaring a Global Class Instance in a C++ file - Stack Overflow
Which is better way to declare global variable in cpp
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
// myclass.h
class MyClass {
public:
MyClass();
void foo();
// ...
};
extern MyClass g_MyClassInstance;
// myclass.cpp
MyClass g_MyClassInstance;
MyClass::MyClass()
{
// ...
}
Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.
First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).
But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used).
class MyVar
{
public:
static MyVar& getGlobal1()
{
static MyVar global1;
return global1;
}
static MyVar& getGlobal2()
{
static MyVar global2;
return global2;
}
// .. etc
}
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()
{
// ...
}
It is just a static object. It is treated like any other global variable.
It will not be tied to any stack frames and will be created when the anything in the file is loaded for the first time.
Generally, people will not recommend relying on globals from a design perspective. It depends though, they can be reasonable.
If you are doing any sort of threading they can be an issue. You also want to minimize different parts of your application knowing that things are global variables, it leads to a lot of spaghetti code.
If the variable is not referenced outside of the file, or for cross-cutting concerns, then sometimes it can be a good thing.
The best advice is to avoid it when you can, don't over design it when you can't.
Objects that are global variables (or more precisely variables "at namespace scope") have static storage duration. This means they live until the end of the program, and they are initialized during program startup (either during the static or the dynamic initialization phase).
The order of initialization is not generally specified except that all such global objects are initialized before main() is called, and that the initialization does not introduce data races.
(Common techniques to sequence mutually dependent global initialization is to replace naked global variables with a global getter function and a block-static variable:
Foo & getFoo() { static Foo impl; return impl; }
Now any other global using getFoo() in its own constructor will be initialized after impl.)
std::string var;
vs
class Var {
static std:string var;
};The storage-class keyword extern causes the problem. You can't specify this for a class definition. And you don't need it anyway: Your class definition will be accessible from anywhere (provided you #include the file it's defined in).
You don't need extern, and it is not even legal in C++ to declare classes as extern. Any class is accessible from anywhere else as long as you don't mess with compiler-specific visibility flags and multiple shared objects (i.e. GCC visibility) and don't create a nested, protected or private class.
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.