Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

#define inside namespace 2

Status
Not open for further replies.

titanandrews

Programmer
Feb 27, 2003
130
US
Hi,
I have something like this in a header file:
Code:
namespace MY_STUFF
{
    #define THING_A "A thing"
    #define THING_B "Another thing"
}
and I want to access these from a function in my .cpp file.
If I do this:
Code:
void MyFunc()
{
    using namespace MY_STUFF;
    CString strTmp(THING_A);
}
it works! But I want to fully qualify the name without using "using namespace"
I tried
CString strTmp(MY_STUFF::THING_A); but compiler complains, "
error C2589: 'string' : illegal token on right side of '::'"

Any idea?



many thanks,

Barry
 
Can a #define even be included in a namespace?? I don't think so. Instead, the preprocessor replaces all instances of THING_A with "A thing". So then the compiler sees MY_STUFF::"A thing". Of course, that doesn't work.

Instead of using #defines, use a constant string value.
Code:
namespace MY_STUFF
{
    const CString THING_A = "A thing"; // or
    const char THING_B[] = "Another thing";
}
 
Remember the preprocessor has been and done its job before the compiler even sees the code. Preprocessors have no idea what a namespace is or any other scope for that matter and so the best you can hope for using macros is a quick #define then use macro then immediately #undef it and that will give an illusion of scope for the macro but as suggested best solution are const objects.
 
Status
Not open for further replies.

Similar threads

Replies
2
Views
318
Replies
4
Views
181
Replies
4
Views
179

Part and Inventory Search

Sponsor

Back
Top