Using define directive to get the namespace name - c++

Having such a simple C++ code:
#include <iostream>
#define NS NS_Static
#define MAKESTRING(x) #x
namespace NS {
int global_x = 8;
void print_global_x() {
std::cout << MAKESTRING(NS) << "::global_x: " << global_x << std::endl;
}
}
I'h expected to get on output NS_Static::global_x: 8 BUT getting just NS::global_x: 8. I've asked a similar question earlier and the user Eljay provided me an answer to use such an extra code:
#define NS Static
#define MAKESTRING_HELPER(x) #x
#define MAKESTRING(x) MAKESTRING_HELPER(x)
It finally works but can someone please explain my why my original approach doesn't work?
Shouldn't the preprocessor (in my original approach) AT FIRST (since it's the first macro defined) run NS NS_Static macro resulting in
NS_Static and then pass that NS_Static to the stringizing MAKESTRING(x) #x macro resulting in expected NS_Static string?

That's how stringizing (#x) in the C preprocessor works.
Unlike normal parameter replacement, the argument is not macro-expanded first.
To get the parameter to macro-expand, add another layer of indirection (a no-op macro like you've discovered, will suffice).

From https://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan
Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringized or pasted with other tokens.
In your original function:
#define NS NS_Static
#define MAKESTRING(x) #x
The marco argument is stringized, so NS will not be replaced by NS_Static.

Related

How to redefine a C++ #define macro using information from the macro itself?

Is it possible to redefine a C++ #define macro using information from the macro itself? I tried the code below, but because of the way the macros are evaluated the output was not what I expected.
#include <iostream>
#define FINAL_DEFINE "ABC"
#define NEW_DEFINE FINAL_DEFINE "DEF" // Want ABCDEF
#undef FINAL_DEFINE
#define FINAL_DEFINE NEW_DEFINE // Want ABCDEF, but get empty?
int main ()
{
std::cout << FINAL_DEFINE << std::endl; // Want ABCDEF, but doesn't compile.
}
Macros in macro bodies are never expanded when the macro is defined -- only when the macro is used. That means that the definition of NEW_DEFINE is not "ABC" "DEF", it is exactly what appears on the #define line: FINAL_DEFINE "DEF".
So when you use FINAL_DEFINE, that gets expanded to NEW_DEFINE which then gets expanded to FINAL_DEFINE "DEF". At this point it will not recursively expand FINAL_DEFINE (as that would lead to an infinite loop) so no more expansion occurs.
If your compiler supports push_macro & pop_macro pragma directives, you could do this:
#include <iostream>
#define FINAL_DEFINE "ABC"
#define NEW_DEFINE FINAL_DEFINE "DEF"
int main ()
{
std::cout << FINAL_DEFINE << std::endl; // Output ABC
#pragma push_macro("FINAL_DEFINE")
#define FINAL_DEFINE "XXX"
std::cout << NEW_DEFINE << std::endl; // Output XXXDEF
#pragma pop_macro("FINAL_DEFINE")
}
After preprocessing all FINAL_DEFINE in the code will be replaced with the last thing it defined and then going to compiling step.
So you cannot redefine the macro like you want.
Your compiler should warn you about that.

Nested macro expansion

I'm not sure if that's the right terminology to use, however my problem is that the a macro call ("PLUGIN_NAME") as a parameter to another macro call ("IMPLEMENT_MODULE"), which in turn prints it as a string, prints that argument as the macro call ("somePLUGIN_NAME") rather than the expanded result ("someSomePluginName").
Note that "IMPLEMENT_MODULE" is an API call so I can't change that.
#define IMPLEMENT_MODULE(name) something##name
#define PLUGIN_NAME SomePluginName
#define _STR(s) #s
#define STR(s) _STR(s)
#define PLUGIN_NAME_STR STR(PLUGIN_NAME)
int main()
{
string expected = "somethingSomePluginName";
string actual = STR(IMPLEMENT_MODULE(PLUGIN_NAME));
printf("expected: %s || actual: %s\n", expected.c_str(), actual.c_str());
assert(expected == actual);
}
I've put it here:
http://codepad.org/FRzChJtD
You need another helper macro to concatenate the preprocessor tokens after macro-expanding them:
#define IMPLEMENT_MODULE_2(A, B) A##B
#define IMPLEMENT_MODULE(name) IMPLEMENT_MODULE_2(something, name)
See working example here
This technical explanation is that macro expansion will not occur if the token-pasting (##) or stringizing operator (#) are found by the preprocessor.

Stringizing operator in C/C++

I am trying to use the stringizing operator #, but I get the error stray ‘#’ in program. Here is how I am using it.
#define STR "SOME_STRING"
#define BM 8
#define NUM_OF_THREADS 8
#define VER_STR (STR #BM #NUM_THREADS)
I expect to get SOME_STRING88 for VER_STR but instead get an error. What mistake am I doing?
You need to turn the numerical constants into a string. However, #BM is an error, since the syntax is only valid for macro parameters.
So you need to force en expansion through an intermediate macro. And you may as well have a STRINGIFY macro to do it:
#include <iostream>
#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)
#define STR "SOME_STRING"
#define BM 8
#define S_BM STRINGIFY(BM)
#define NUM_OF_THREADS 8
#define S_NUM_OF_THREADS STRINGIFY(NUM_OF_THREADS)
#define VER_STR STR S_BM S_NUM_OF_THREADS
int main() {
// your code goes here
std::cout << VER_STR;
return 0;
}
You can see the above in action at http://ideone.com/cR1KZP
EDIT
As Magnus Hoff pointed out, you can invoke STRINGIFY directly as well:
#define VER_STR STR STRINGIFY(BM) STRINGIFY(NUM_OF_THREADS)

Macro increase value and then concatenate

I want to create a recursive Macro the will create the "next" class.
Example:
#define PRINTME(indexNum) class m_##(indexNum+1) { }
The indexNum + 1 is evaluated as an int, and won't concatenate to the class name.
How can I cause the compiler to evaluate that, before concatenating?
If you want to generate unique class names every time the PRINTME is invoked then, following is one way:
#define CONCATE1(X,Y) X##Y
#define CONCATE(X,Y) CONCATE1(X,Y)
#define PRINTME class CONCATE(m_,__COUNTER__) {}
__COUNTER__ is an extension in gcc and I am not sure if it's present in other compilers. It's guaranteed that compiler will add 1 every time this macro is invoked.
(In this case, you cannot use __LINE__ or __FILE__ effectively.)
Demo.
The simple answer is that you can't. The preprocessor generally deals in text and tokens; the only place arithmetic is carried out in in #if and #elif directives.
Also, macro expansion isn't recursive. During expansion, the macro being expanded is disabled, and is not available for further substitution.
Well it is doable, based on your motivation and ability to endure ugly code. First off define increment macro:
#define PLUS_ONE(x) PLUS_ONE_##x
#define PLUS_ONE_0 1
#define PLUS_ONE_1 2
#define PLUS_ONE_2 3
#define PLUS_ONE_3 4
#define PLUS_ONE_4 5
#define PLUS_ONE_5 6
#define PLUS_ONE_7 8
#define PLUS_ONE_8 9
#define PLUS_ONE_9 10
// and so on...
You can't just use PLUS_ONE(x) in concatenation operation, since preprocessor won't expand it. There is a way, however - you can abuse the fact that the preprocessor expands variadic arguments.
// pass to variadic macro to expand an argument
#define PRINTME(indexNum) PRINTME_PRIMITIVE(PLUS_ONE(indexNum))
// do concatenation
#define PRINTME_PRIMITIVE(...) class m_ ## __VA_ARGS__ { }
Done!
PRINTME(1); // expands to class m_2 { };
Have you considered using templates instead?

How do I turn a macro into a string using cpp?

GNU's cpp allows you to turn macro parameters into strings like so
#define STR(x) #x
Then, STR(hi) is substituted with "hi"
But how do you turn a macro (not a macro parameter) into a string?
Say I have a macro CONSTANT with some value e.g.
#define CONSTANT 42
This doesn't work: STR(CONSTANT). This yields "CONSTANT" which is not what we want.
The trick is to define a new macro which calls STR.
#define STR(str) #str
#define STRING(str) STR(str)
Then STRING(CONSTANT) yields "42" as desired.
You need double indirection magic:
#define QUOTE(x) #x
#define STR(x) QUOTE(x)
#define CONSTANT 42
const char * str = STR(CONSTANT);