Dear formum members,
I have a rather strange problem when trying to define variables inside a namespace. My original idea was to use those variable names and in various functions of the c++ code. I did very simple definition of my variables in
nstest.h
as follows
1 2 3 4 5 6
|
#ifndef NSTEST_H
#define NSTEST_H
namespace nstest {
Int var1;
Int var2;
}
|
If I later on include this file in the main as follows:
1 2 3 4
|
#unclude “nstest.h”
Using namespace nstest;
Int main() {
…
|
I can compile and run. However if I try to use the same procedure in one f my functions I get violation of the “one definition rule”.
1 2 3 4
|
nsf.o:(.bss+0x0): multiple definition of `nstest::var1'
main.o:(.bss+0x0): first defined here
nsf.o:(.bss+0x4): multiple definition of `nstest::var2'
main.o:(.bss+0x4): first defined here
|
My obvious guess would be to use
extern int var1 ;
for my variables in the namespace. However this produces an error likewise.
1 2 3 4 5
|
main.cpp:(.text+0x976): undefined reference to `nstest::var1'
main.cpp:(.text+0x97c): undefined reference to `nstest::var2'
nsf.o: In function `nsf(int, int)':
nsf.cpp:(.text+0x1a): undefined reference to `nstest::var1'
…..
|
My general idea of doing this was to see what are the differences between the namespaces and Fortran modules. In Fortran it is possible to have module files, which can contain functions, names and variables. If you include them in some of your functions or in the main, you have access to everything that is contained inside them.
I don't understand why this makes problems, I have used the same method to define classes inside a namespace, and no problems occurred. I guess that I have some misunderstanding about the namespaces. I would be very grateful if someone can help me understand what am I doing wrong.
Thanks,