2

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.

masterop
  • 184
  • 1
  • 12
  • 5
    Macros are preprocessor directives (and work by pure textual replacement), you cannot scope them to namespaces – UnholySheep Nov 24 '17 at 15:22
  • 2
    Macros don't respect namespaces. They are resolved before namespaces are even parsed. So this becomes `A::do{...}` which is obviously wrong. – Ext3h Nov 24 '17 at 15:25
  • *"get the filename and linenumber"* : you might use [std::experimental::source_location](http://en.cppreference.com/w/cpp/experimental/source_location) if available for you. – Jarod42 Nov 24 '17 at 15:29
  • [this](https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives) is probably worth a read – UKMonkey Nov 24 '17 at 15:43
  • @Ext3h Thanks for this specific explanation. – masterop Nov 24 '17 at 15:45

1 Answers1

2

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");
}
YSC
  • 38,212
  • 9
  • 96
  • 149
  • This resolves the error message but then I get the error message error: ‘B’ has not been declared. To resolve this I have to use the namespace name in MACRO like A::B::func(); – masterop Nov 24 '17 at 15:34
  • @masterop You need to define your macro to use `A::B::func` ;) – YSC Nov 24 '17 at 15:37