masterop masterop - 6 months ago 92
C++ Question

Macro inside namespace giving expected unqualified-id before 'do' error

I am trying to use macro within namespace for logging purpose to get the filename and linenumber.
Here is a simplified version of code that is generating the error.

#include <iostream>
using namespace std;

namespace A
{
#define MACRO(a) \
do { \ //error: expected unqualified-id before 'do'
B::func() \
} while(0)

class B
{
public:
static void func(){cout << "called from MACRO\n";}
};
}

int main() {
A::MACRO("something"); //note: in expansion of macro ‘MACRO’
return 0;
}


I also tried to define the macro using another format like

#define MACRO(message) \
( \
{ \
B::func() \
} \
)


but same error. Here is a link to a minimal working example.

This gave me the idea to use macros in this way. But in that question no class is being used and as I mentioned this is a simplified version of what I am trying to achieve.

YSC YSC
Answer Source

Macros are a preprocessing concept. The preprocessor does not have a notion of namespace.

You could define your macro inside namespaces, but you'll use it with an unqualified name:

namespace n {
#define MACRO(x)
}

int main()
{
    MACRO("something");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download