|
-
April 19th, 2004, 03:23 PM
#1
help with namespaces...
hello everyone,
I'm having some issues with namespaces and was wondering if anyone new the problem.
First of all I have a namespace with a few global variables and functions like the following.
mynamespace {
HANDLE hMyEvent;
int i;
int j;
void MyFunc1();
void MyFunc2();
}
I have multiple c++ files that use this namespace to access the global data, however I get linking errors from the variables unless I preceede their declaration with "static".
Another big issue I'm facing is that it seems that each file that uses the variables by calling: mynamespace::i = value has their own local copy. That is, when I set an event from the namespace in one file, another file doesn't see these modifications.
the namespacee is defined in mynamespace.h and implemented in mynamespace.cpp.
Files that use the namespace include mynamespace.h and then access the variables or functions by using the namespace name and scope resolution operator, mynamespace::.
Anyone have some ideas for these problems.
Thanks.
rdalton
-
April 19th, 2004, 03:42 PM
#2
Namespace usage:
Code:
namespace mynamespace
{
//whatever
}
namespace
{
//equivalent to file scope static...
// i.e. unnamed namespace
}
mynamespace::whatever....
For details have a look to your favorite C++ textbook.
-
April 19th, 2004, 03:48 PM
#3
I had a typo in my prior post,
I do declare my namespace like:
namespace mynamespace {
HANDLE hMyEvent;
int i;
int j;
void MyFunc1();
void MyFunc2();
}
so it is not anonymous.
my question deals more with the scope of the variables in the namespace. I suppose I have to declare my globals OUTSIDE of the namespace in my header file and then use extern inside the namespace. Does this seem right?
-
April 19th, 2004, 04:33 PM
#4
No it doesn't. You can't declare variables in the header without using extern. That will lead to one variable being defined for each of the cpp files that include the header. This is the reason for the linker errors you were recieving. Putting static in front of the definition, will cause one copy of the variable to be created for each cpp file, even though they have the same name. (Another of the problems you were seeing.)
Simply do this:
Code:
// header.h:
namespace whatever
{
extern int some_variable;
}
// source.cpp
#include "header.h"
namespace whatever
{
int some_variable = 0;
}
// some_other_source.cpp
#include "header.h"
void func()
{
whatever::some_variable = 100;
}
-
April 19th, 2004, 04:57 PM
#5
thanks Assmaster...that's exactly what I was looking for!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|