Presuming that your C++ compiler supports them, is there any particular reason not to use __FILE__
, __LINE__
and __FUNCTION__
for logging and debugging purposes?
I'm primarily concerned with giving the user misleading data—for example, reporting the incorrect line number or function as a result of optimization—or taking a performance hit as a result.
Basically, can I trust __FILE__
, __LINE__
and __FUNCTION__
to always do the right thing?
In rare cases, it can be useful to change the line that is given by
__LINE__
to something else. I've seen GNU configure does that for some tests to report appropriate line numbers after it inserted some voodoo between lines that do not appear in original source files. For example:Will make the following lines start with
__LINE__
100. You can optionally add a new file-nameIt's only rarely useful. But if it is needed, there are no alternatives I know of. Actually, instead of the line, a macro can be used too which must result in any of the above two forms. Using the boost preprocessor library, you can increment the current line by 50:
I thought it's useful to mention it since you asked about the usage of
__LINE__
and__FILE__
. One never gets enough surprises out of C++ :)Edit: @Jonathan Leffler provides some more good use-cases in the comments:
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
Personally, I'm reluctant to use these for anything but debugging messages. I have done it, but I try not to show that kind of information to customers or end users. My customers are not engineers and are sometimes not computer savvy. I might log this info to the console, but, as I said, reluctantly except for debug builds or for internal tools. I suppose it does depend on the customer base you have, though.
__FUNCTION__
is non standard,__func__
exists in C99 / C++11. The others (__LINE__
and__FILE__
) are just fine.It will always report the right file and line (and function if you choose to use
__FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never effect performance in any way.