I'm working on a project and have a problem that I believe can be solved with macros, but given the nature of the issue I don't have the experience to write one myself.
Here's what I would expect as input and output of the #define macro:
Inputting code such as this
printf(foobar(Hello World.));
Should result in the preprocessor producing code that reads:
printf((char *)(std::string("")+'H'+'e'+'l'+'l'+'o'+' '+'W'+'o'+'r'+'l'+'d'+'.').c_str());
I'm assuming something this complicated is possible, and I hope one of you guys can help me out.
I NEED IT TO BE A MACRO, I DO NOT want a string constant anywhere.
Uh, I fear it is impossible (unless I don't know something). I believe there is no macro to split a given input token (eg Hello) into characters building it (H ello)
There were some attempts to do such thing, but I fear it is not exactly what you need:
C++: Can a macro expand "abc" into 'a', 'b', 'c'?
"More powerful precompiler" ?
Try this topic: Replacements for the C preprocessor
The only solution I can think of is to run your code through a suitable script (probably just some light awk ), that does the substitution before your code reaches the pre-compiler.
Depending on your environment you could do this as a "Pre-Build Event" in Visual Studio, or just add a step directly into your makefile.
Macros are basically substitution or addition of strings. You could do this with a pre-processor of your own, but the standard pre-processor won't split strings into component parts.
How about this: Put all these (assuming there is more than one) 'macros' in a separate file. Write a program that translates them into the expansion you require and then include THAT file in your c program? You could then make the expansion program part of your make file so it's always up to date. Using a separate file makes the expansion program much easier than parsing ac/c++ file.
Since you're looking for a narrow, direct answer to your question and without suggestions, here goes:
This is impossible. You must find a different solution to whatever it is you're trying to achieve.
Have you tried:
#define toString(x) #x
You can use it after like this:
printf("%s", toString(hello world));
Don't try to use printf directly with the string because you can have format specifier in the string.
printf(toString(hello world)); //wrong, you can have for example %d in the string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.