Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ concatenating __FILE__ and __LINE__ macros?

Tags:

c++

I want my exception messages to contain info about the exception location.

So I would like to have some like thing this.

#define LOCATION __FILE__ " : " __LINE__

throw std::exception(std::string("ABCD. ") + LOCATION);

That define is obviously incorrect. How to achieve this?

like image 596
NFRCR Avatar asked Oct 13 '13 08:10

NFRCR


1 Answers

You need to expand that macro in two levels:

#define S1(x) #x
#define S2(x) S1(x)
#define LOCATION __FILE__ " : " S2(__LINE__)

Here is the reason:

You need expand __LINE__ in two levels, before passing it to #x.

First of all, using operator # in a function-like macro, it has to be followed by a macro parameter but __LINE__ is not a parameter, so compiler complains it's a stray operator.

On the other hand, __LINE__ itself is a macro and contains current line number, it should be expanded to the number before using it with #, otherwise, you will get string "__LINE__" instead of a number.

Macro S2(__LINE__) expands __LINE__ to a line number, then we pass the line number to #x.

like image 80
masoud Avatar answered Nov 08 '22 05:11

masoud