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.
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With