Token pasting and __LINE__ - c++

I'm writing a simple macro to show TRACE information.
This is what I'm using ,
#ifdef __DEBUG__
#define TRACE { PrintErrorMsg("Trace exception at " __FILE__ "LineNo:"##(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif
This is working with FILE, but it doesn't seems to work with LINE ,
Any idea how could I deal with this. I already tried stringing operator too.Which is as
bellow.
#ifdef __DEBUG__
#define TRACE { PrintErrorMsg("Trace exception at " __FILE__ "LineNo:"#(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif
and without parms and with double parms , ex - __LINE__ or ((__LINE__))
Any idea how could I deal with this problem?
And I come up with this,
#ifdef __DEBUG__
#define ERROR_MSG_BUF_SIZE 1024
#define TRACE { char * error_msg_buffer = new char[ERROR_MSG_BUF_SIZE]; \
sprintf(error_msg_buffer,"Trace Exception at file: %s ,Line : %d , Function %s \n",__FILE__,__LINE__,__FUNCTION__);\
PrintErrorMsg(error_msg_buffer );\
delete[] error_msg_buffer;}
#else
#define TRACE
But I want to do it without using sprintf , just only by stringing and token pasting.
Any idea?
#endif
--Thanks in advance--

When you try to stringize something with #x, that x must be a macro parameter:
#define FOO #__LINE__ /* this is not okay */
#define BAR(x) #x /* this is okay */
But you cannot simply say BAR(__LINE__), because this will pass the token __LINE__ into BAR, where it is immediately turned into a string without expansion (this is by design), giving "__LINE__". The same thing happens with the token-pasting operator ##: expansion of their operands never happens.
The solution is to add indirection. You should always have these in your codebase somewhere:
#define STRINGIZE(x) STRINGIZE_SIMPLE(x)
#define STRINGIZE_SIMPLE(x) #x
#define CONCAT(first, second) CONCAT_SIMPLE(first, second)
#define CONCAT_SIMPLE(first, second) first ## second
Now STRINGIZE(__LINE__) turns to STRINGIZE_SIMPLE(__LINE__) which gets fully expanded to (for example) #123, which results in "123". Phew! I leave STRINGIZE_SIMPLE around on the off chance I want the original behavior. So your code would be something like:
#include <iostream>
#define STRINGIZE(x) STRINGIZE_SIMPLE(x)
#define STRINGIZE_SIMPLE(x) #x
#define TRACE() \
PrintErrorMsg("Trace exception in " __FILE__ \
" at line number " STRINGIZE(__LINE__) \
" in function " __FUNCTION__ ".")
void PrintErrorMsg(const char* str)
{
std::cout << str << std::endl;
}
int main()
{
TRACE();
}

You need this kind of silliness, unfortunately.
#include <stdio.h>
#define TRACE2(f,l) printf("I am at file: " f " and line: " #l "\n")
#define TRACE1(f,l) TRACE2(f,l)
#define TRACE() TRACE1(__FILE__, __LINE__)
int main(void)
{
TRACE();
TRACE();
}
I am at file: test.cpp and line: 9
I am at file: test.cpp and line: 10

Related

How to concat __func__ and __LINE__ in a macro definition

I would like to define a macro to concat __func__ (or __FUNCTION__) with __LINE__:
The following works fine:
// macro_test.cc
#include <iostream>
#define STR2(X) #X
#define STR(X) STR2(X)
#define FILE_LOCATION __FILE__ ":" STR(__LINE__) " "
int main() {
std::cout << FILE_LOCATION << "is <file_name>:<line_number>" << std::endl;
return 0;
}
And here is the output
$ ./a.out
macro_test.cc:8 is <file_name>:<line_number>
However the following gives a compilation error (I just replaced __FILE__ with __func__):
// macro_test.cc
#include <iostream>
#define STR2(X) #X
#define STR(X) STR2(X)
#define FUNC_LOCATION __func__ ":" STR(__LINE__) " "
int main() {
std::cout << FUNC_LOCATION << "is <function_name>:<line_number>" << std::endl;
return 0;
}
~$ gcc macro_test.cc
macro_test.cc: In function ‘int main()’:
macro_test.cc:5:32: error: expected ‘;’ before string constant
#define FUNC_LOCATION __func__ ":" STR(__LINE__) " "
^
macro_test.cc:8:16: note: in expansion of macro ‘FUNC_LOCATION’
std::cout << FUNC_LOCATION << "is <function_name>:<line_number>" << std::endl;
Does anyone know the reason for this and how can I achieve this?
I am using gcc 5.4.0 on Linux (Ubuntu 18.04).
gives a compilation error [...] anyone know the reason for this
__func__ is a variable:
static const char __func__[] = "function-name";
It is not to a (string) literal (to which for example __FILE__ "expands".)
(docs are here: https://gcc.gnu.org/onlinedocs/gcc/Function-Names.html)
Instead of trying to stitch together incompatible types into a single string, you could have an immediately invoked function expression (borrowing from JavaScript terminology) as the macro implementation.
Since it is being immediately executed, I pass in the two preprocessor identifiers as parameters.
They shouldn't be baked into the body of the lambda because then the __func__ will reflect the lambda rather than the routine invoking the lambda.
#include <sstream>
#define FUNC_LOCATION \
[](auto fn, auto ln) { \
std::stringstream ss;
ss << fn << ":" << ln << " "; \
return ss.str(); \
}(__func__, __LINE__)
int main() {
std::cout << FILE_LOCATION << "is <file_name>:<line_number>" << std::endl;
return 0;
}

Preprocessing string concatenation

I would like to concatenate the 3 following strings to produce a good debug output, by using std::setw() after.
__ FILENAME__ , ":" and LINE
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define AT __FILENAME__ ":" __LINE__
#ifdef DEBUG
#ifdef VERBOSE
#define printDebug(x) std::cout << AT << x << std::flush
#else
#define printDebug(x) std::cout << x << std::flush
#endif
#else
#define printDebug(x)
#endif
But actually I receive errors saying that a ";" field is missing before ":". Does someone have an idea ?
I actually call the printDebug() function like that :
printDebug("[SUCCESS] Receiving Message");
You can concatenate string literals by putting them alongside each other.
":" is a string literal.
__LINE__ expands to a numeric literal, not string one.
__FILENAME__ doesn't expand to a literal at all. It expands to an expression.
There is a way to get a string literal out of __LINE__, but you can't make __FILENAME__ a string literal.
You don't need to use literal concatenation here at all. You can simply do this:
#ifdef VERBOSE
#define printDebug(x) std::cout << __FILENAME__ << ":" << __LINE__ << x << std::flush

How to get the definition of a macro as a string literal?

Say in a header, which I do not want to read myself but which I do include, I have
#define A B
#define B C
Now
#define STR(name) # name
defines a macro that gives me the name of any macro as a string, and
#define EXP_STR(name) STR(name)
defines a macro that gives me the full expansion of any macro as a string. So
cout << STR(A) << EXP_STR(A) << endl;
will print AC.
Is there any way to get "B" from A using some macros?
Since you can write
#define B C
#define A B
#define STR(name) # name
#define EXP_STR(name) STR(name)
and the
cout << STR(A) << EXP_STR(A) << endl;
will output exaclty the same, it means that it's not possible.
When you do this
#define A B
and then
#define B C
now this means that A will be substituted by C and not B, so there will be no way to do it because when the cout line is reached the preprocessor had already substituted A by C.
So the short answer is, it's not possible because the preprocessor would have replaced A with C before the file is compiled.
Yeah, it's possible. You just have to use a couple of cheats.
#undef B before #define EXP_STR
Use a few more levels of indirection
For example:
#define A B
#define B C
#define _TEMP_VAR B // so that it can be redefined later
#undef B // so that EXP_STR(A) will return "B"
#define EXP_STR__(x) (x)
#define EXP_STR_(x) EXP_STR__(#x)
#define EXP_STR(x) EXP_STR_(x)
#define STR(x) # x
#define B _TEMP_VAR // now you can still access A normally, defined to B (defined to C)
A test program to prove it:
#include <stdio.h>
int main(void)
{
printf( "EXP_STR(A) = %s\n", EXP_STR(A) );
printf( "STR(A) = %s\n", STR(A) );
}
Output:
EXP_STR(A) = B
STR(A) = A

C++ macro with variable arguments

1.#define debug(...) printf( __VA_ARGS__)
2.#define debug(...) std::cout<< __VA_ARGS__
Apparently, 1 is ok, 2 will get error when compiles.
Is there any possibility to use "std::cout" with variable arguments?
What's the point of this macro?
'debug' macro use to print something to debug the code.
void test(const classtype1 &obj1,const classtype2 &obj2)
{
// rewrite operator<<
debug(obj1,obj2);
//if use printf, I must call tostring method(or something likes that) to
//series the object to string.
debug(obj1.tostring(),obj2.tostring());
...
}
You can do something like:
#define DEBUG(x) do { std::osacquire( std::cerr ) << __FILE__ << ":" << __LINE__ << " " << x << std::endl; } while (0);
And then wherever you want to use the macro:
DEBUG( obj1.tostring() + " some stuff " + obj2.tostring() )

Trouble creating assert function

This is my assert function (it wont compile "error C2110: '+' : cannot add two pointers"):
#define CHAR(x) #x
template<typename T>
inline void ASSERT(T x)
{
if(!x)
{
std::string s("ERROR! Assert " + CHAR(x) + " failed. In file " + __FILE__ +
" at line " + __LINE__ + ".");
std::wstring temp(s.length(), L' ');
std::copy(s.begin(), s.end(), temp.begin());
getLogger().Write(temp);
}
}
Any idea of how to fix it?
String Literals are easily reduced to char pointers, which cannot be added as you try to do with "ERROR! Assert " + CHAR(x) + " failed. In file ".... However, C++ has the handy feature of doing this automatically before compilation! (the preprocessor does this). Even better, it has a handy tool for making wide strings at compile time. So, you want:
#define _T(x) L ## x
#define CHAR(x) #x
#define CHAR2(x) CHAR(x)
#define ASSERT(x) ASSERT2(x, CHAR(x), __FILE__, CHAR2(__LINE__))
#define ASSERT2(x, t, f, l) \
if(!x) \
getLogger().Write(L"ERROR! Assert " _T(t) L" failed. In file " _T(f) L" at line " _T(l) L".");
http://ideone.com/0ibcj
The compiler error is quite clear; you are trying to apply the + operator to string literals. A quick way to fix it is enclosing the first string literal in std::string().
As #James McNellis pointed out, note that FILE and LINE will point to the file and line of the assert function declaration.
You cannot use the + operator to concatenate two char*s; you need printf or some sort of thing for that.
"ERROR! Assert " is a null-terminated, C-style string. You can't execute operator+ on it.
A few issues:
Generally an assert should break into the debugger or dump if one is not attached. This will not.
As already mentioned, your LINE and FILE require use in a macro
You need a couple "helper" macros to get the strings working properly
Try something along these lines:
#define ASSERT_QUOTE_(x) #x
#define ASSERT_QUOTE_(x) ASSERT_QUOTE_(x)
#define MY_ASSERT(cond) \
if(cond) {} else { \
std::stringstream ss; \
ss << "ERROR! Assert " << ASSERT_QUOTE(cond) << " failed. In file " << __FILE__ << " at line " << __LINE__ << "."; \
getLogger().Write(ss.str()); \
}
Be careful trying to use STL here however. I suggest you have your logger's Write() function take variable arguments and process them with printf() or perhaps boost::format