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
class DataContainer
{
public:
static Object data1 ;
static Object data2 ;
} ;
Object DataContainer::data1 ;
Object DataContainer::data2 ;
However there's also extern
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 extern
in 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 static
members 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 namespace
prevent pollution of the global namespace with potentially common identifiers like data1
,
// File: globaldata.h
#ifndef GLOBALDATA_H
#define GLOBALDATA_H
#include "Object.h" // Definition of Object might be here
namespace GlobalData
{
extern Object data1;
extern Obejct data2;
}
#endif GLOBALDATA_H
.
// File: globaldata.cc
#include globaldata.h
namespace GlobalData
{
Object data1;
Object data2;
}
Then you can access them in other places like this.
#include "globaldata.h"
// Does something with global data
void f()
{
GlobalData::data1.doSomething();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With