-
Preprocessor Precedence
Here's what I'm trying to do.... to make a macro that will give it an error as a c-string, and it will give me a c-string with the line and file and the error, all put together. Then I can use that string to display, or whatever. Here's what I have:
Code:
#include <iostream>
using namespace std;
#define FlagF(Line,File,Error) ( "Line " #Line ", File " File ", Error " Error )
#define Flag(Error) ( FlagF( __LINE__, __FILE__, Error ) )
int main()
{
cout << Flag( "Blah!" ) << endl;
}
...and for output I get this:
"Line __LINE__, File c:\documents and settings\evan ovadia\my documents\visual studio projects\combination\main.cpp, Error Blah!"
Why is it saying __LINE__? I stringized it, but it was supposed to stringize the line number AFTER __LINE__ did its job. Is there a way to make the precedence of __LINE__ higher than the stringizer operator? If there isn't, is there any way to make a macro like I tried to make?
Thanks!
-
The preprocessor is a strange animal.
Code:
#define str(x) #x
#define FlagF(Line,File,Error) ( "Line " str(Line) ", File " File ", Error " Error )
#define Flag(Error) ( FlagF( __LINE__, __FILE__, Error ) )
-
It is indeed a strange animal...
That code snippet produces:
"Line (__LINE__Var+1), File c:\documents and settings\evan ovadia\my documents\visual studio projects\combination\main.cpp, Error Blah!"
Where's Var+1 come from...?
-
This is explained here. You need to treat __LINE__ as an integer expression rather than a numeric constant and do a run-time conversion.
-
Why don't you make FlagF an inline function instead?
-
because I put a new file into the system root, called Verd.h. I put macros and definitions and stuff in there, but I can't put any code, because all the files in all my project include it. Since they all include it, if I put any function code in there, it'll be copied and waste space.
-
Salem's advice works well on gcc/g++
You're using a MS compiler which doesn't do what you want.
You can use precompiler directives to use a dinamic calculation when not using gcc.
Code:
#ifdef __GNUC__
#define str(x) #x
#define FlagF(Line,File,Error) ( "Line " str(Line) ", File " File ", Error " Error )
#define Flag(Error) ( FlagF( __LINE__, __FILE__, Error ) )
#else
#define Flag(Error) (( std::string("Line")+__LINE+" File "+ __FILE__+" Error "+ Error ).c_str())
#endif