I’d like to make program-wide data in a C++ program, without running into pesky LNK2005 errors when all the source files #includes this “global variable repository” file.
I have 2 ways to do it in C++, and I’m asking which way is better.
The easiest way to do it in C# is just public static members.
C#:
public static class DataContainer
{
public static Object data1 ;
public static Object data2 ;
}
In C++ you can do the same thing
C++ global data way#1:
class DataContainer
{
public:
static Object data1 ;
static Object data2 ;
} ;
Object DataContainer::data1 ;
Object DataContainer::data2 ;
However there’s also extern
C++ global data way #2:
class DataContainer
{
public:
Object data1 ;
Object data2 ;
} ;
extern DataContainer * dataContainer ; // instantiate in .cpp file
In C++ which is better, or possibly another way which I haven’t thought about?
The solution has to not cause LNK2005 “object already defined” errors.
If you absolutely have to have some global objects then the simplest way is to just to declare them
externin a header file included anywhere that needs access to them and define them in a single source file.Your way #1 uses a class with only
staticmembers which means that it is essentially doing the job of a namespace so why not just use a namespace?Way #2 aggregates both objects in a single class but if there is no true interdependency between the two objects there is no particular benefit to this.
I’d recommend putting the objects in a
namespaceprevent pollution of the global namespace with potentially common identifiers likedata1,.
Then you can access them in other places like this.