shadeglare
shadeglare

Reputation: 7536

C++ macros and namespaces

I've got a problem with using macros in namespaces. The code is

#include <iostream>

namespace a
{
#define MESSAGE_A(message) \
    std::cout << (message) << std::endl;
}

#define MESSAGE_A(message) \
    std::cout << (message) << std::endl;

int main()
{
    //works fine
    MESSAGE_A("Test");
    //invalid
    a::MESSAGE_A("Test")
    return 0;
}

What's the proper variant of using namespaced objects in macros.

Upvotes: 8

Views: 8807

Answers (2)

Macros are handled by the pre-processor, which knows nothing about namespaces. So macros aren't namespaced, they are just text substitution. The use of macros really is discouraged, among other reasons because they always pollute the global namespace.

If you need to print out a message, and you need it to be namespaced, simply use an inline function. The code seems simple enough to be properly inlined:

namespace a
{
  inline void MESSAGE_A(const char* message) 
  {
    std::cout << message << std::endl;
  }
}

Upvotes: 12

ForEveR
ForEveR

Reputation: 55887

It will not work. Macroses knows nothing about namespaces. If you want to use namespaces - you must not use macroses.

Upvotes: 3

Related Questions