Question regarding static variable inside a namespace

Hello all,
in my program I needed a variable, which should be accessible from everywhere.

So I have created a namespace GlobalVariables in file global.h .

The problem is, that it seems that my code is not finding that variable...
it's compiling, but there are warnings

globals.h:7: warning: 'GlobalVariables::test' defined but not used
globals.h:7: warning: 'GlobalVariables::test' defined but not used

which is strange, because I am accessing that variable from my code through "GlobalVariables::test" and there is no warning. But it seems that it's not working.

Anyone knows why ?

Regards
If you need a variable in your program that is accessible from everywhere, you don't need to make a namespace for said variable. All you have to do is initialize the variable before calling main().

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

unsigned short int globalVar;

int main()
{
}
Will this make the variable available to any other class in my program ?

Or do I have to use "extern" in another .cpp files in order to access it ?
Last edited on
You would have to use extern in the .cpp files.

But your approach might not work.

What you need is

globals.h:
1
2
3
4
5
6
7
8
#ifndef globals_h
#define globals_h

namespace Globals {
    extern int test;
}

#endif 


globals.cpp:
1
2
3
4
5
#include "globals.h"

namespace Globals {
    int test = 0;
}

I see...
thank you guys. :)

Regards

p.s.: Why if we remove the extern from globals.h, the macros will not prevent linkage error ?
Last edited on
You don't need to use extern if the variable is fully defined in the header file. Is that what you did? what do you mean by macros? Using namespaces is a good idea so that you can logically group related constants and variables together. I'd be careful about just creating a single dumping ground for all global variables. It is better to create separate namespaces and header files, as needed so that you don't end up with everything in your program depending on 1 file. Programs tend to grow and it is better if you adopt some reasonable guidelines to prepare for this inevitability. If this is a small toy program or assignment, that advice won't matter much though.
Topic archived. No new replies allowed.