Hi
I know this is a noob question, but i just wanted to make sure that I what i'm doing is correct.
I've used the extern keyword to declare the same variables in different .c files, so that the compiler understands that it is supposed to be the same variable, not 2 different variables that i've accidently given the same name.
extern NODE TreeNodes[SIZE]; is included in several of my .c files that all use TreeNodes[x] as the same variable. is this right?
thanks
charlie
Yes... sort of.
What you are doing will do what you are asking. However, for maintainability reasons, it is better to declare this in one header file and include that header file. Even then, global variables are not easily maintainable in themselves as they can be modified anywhere making debugging more difficult, and making documentation
even more necessary than normal.
What I have done in the past in C is to declare the
functions related to the 'global object' in a header file, and define them in the source file. The 'global object' would then be declared as static in the source file near the beginning.
In this way, all code related to the 'global object' (which is no longer accessible out side the source file, so is actually a file scoped object) is located in one spot, implying that they are users of that object.
Alternatively, in C++ if there is only to be one instance of this object, you can use the standard Singleton Pattern, which is a design pattern which enforces only one can be made. This can be done as follows:
Header file: -
class foo
-
{
-
private:
-
foo(); // constructor is only available by those who are foo objects.
-
static foo singleInstance; // This is only one instance.
-
static foo arrayInstance[100]; // There is only one instance of this array.
-
-
public:
-
static foo& getSingleInstance();
-
static foo& getElement(int index);
-
};
-
Source file: -
#include "foo.h"
-
-
// These static variables have access to the private
-
// constructor as they are members of class foo.
-
-
// Execute the default constructor on this instance
-
foo foo::singleInstance();
-
-
// Explicitly stating to use the default constructor on first two elements,
-
// the rest will implicitly use the default constructor.
-
foo foo::arrayInstance={ foo(), foo() };
-
If you don't want to pass out the objects via getSingleInstance() or getArrayInstance(), then you could (if only having a single instance) create static functions that would assume that it was meant for the static instance. If only using an array instance, then you could have static functions that would take an index and work on the instance that resides at that index.
What it comes down to is maintainability. However, if you are making a one shot programme where you hope you don’t have to maintain it or debug it later, maybe this isn’t an issue for you.
Does what I am saying make sense? I hope this helps.
Adrian