Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with variable in namespace

I think I hvae a fundamental misunderstanding of namespace and/or static variable. But I have tried this test code (typed by hand, forgive typos)

test.h:

namespace test{
   static int testNum=5;
   void setNum(int value);
}

main.cpp:

#include <test.h>

int test::setNum(int value){
   testNum=value;
}

int main(){
    test::setNum(9);
    cout<<test::testNum;
}

when I run this I get the value 5, not 9 as I would have expected. It seems almost as if I have two instances of the testNum variable, but that seems to be the exact opposite of what static should be doing. I'm guessing I've made a mistake in assuming that these features were identical to their java equvilants somehow...

I also get an error stating that testNum is declared multuple times if I remove the static from my declaration of testNum, could someone explain why that is the case as well?

Thank you

like image 940
dsollen Avatar asked Jul 13 '12 20:07

dsollen


1 Answers

You might want to make sure your code actually has problems before you post it asking what's wrong ;)

I copy/pasted and fixed your typos, and manually did the include:

#include <iostream>
using namespace std;

namespace test{
   static int testNum=5;
   void setNum(int value);
}

void test::setNum(int value){
   testNum=value;
}

int main(){
    test::setNum(9);
    cout<<test::testNum;
}

result:

$ ./a.out 
9

What you haven't said is what else is in your program. If you have more than just main.cpp, and include your test.h, then each .cpp file will have its own copy of testNum. If you want them to share then you need all but one to mark it as extern.

like image 171
Adam Avatar answered Oct 22 '22 15:10

Adam