C ++ Macros and Namespaces

I have a problem using macros in namespaces. The code

#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 is the correct way to use objects with names in macros.

+8
c ++ macros namespaces
source share
2 answers

Macros are processed by a preprocessor that knows nothing about namespaces. Thus, macros are not replaced with names, it is just a replacement for text. The use of macros is really discouraged, among other reasons, because they always pollute the global namespace.

If you need to print a message, and you want it to be placed in the namespace, just use the built-in function. The code seems simple enough for a proper installation:

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

This will not work. Macros do not know anything about namespaces. If you want to use namespaces, you should not use macros.

+2
source share

All Articles