Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
shadeglare Avatar asked Feb 21 '13 12:02

shadeglare


People also ask

What are namespaces in C?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is macro file in C?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

Are there macros in C?

Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well.


1 Answers

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;
  }
}
like image 172
StoryTeller - Unslander Monica Avatar answered Oct 27 '22 02:10

StoryTeller - Unslander Monica