|Hosting by Solid Eight Studios,PhotoTangler Collage Maker|
Question submitted by (21 August 2000)
|Return to The Archives|
Was wondering if you knew of a compiler directive such as __FILE__ or __LINE__ which inserts
the string name of the current class or
function name? Or if there is another way to get this data? I want to use this functionality
for file logging. I have searched MSDN, the net, and newsgroups and haven't found anything, thanks.
All the GNU compilers on my Linux boxes (including EGCS) support the
__FUNCTION__ variable which is just what you want: a string that contains the
current function name. The WATCOM compiler also supports __FUNCTION__.
Unfortunately, you can't check for the existence of __FUNCTION__ using #ifdef, because (at least in GNU) it's not a preprocessor macro.
Using __FUNCTION__ within a class member (as in "MyClass::MyMemberFunction") will only result in the raw function name ("MyMemberFunction"), not the class::function name. Under the GNU compilers, you can use __PRETTY_FUNCTION__ to get something even better. In this case, the result would be something like "bool MyClass::MyMemberFunction(int, int)". If you're really anal, you could parse the class name out of this, but why bother?
As for a __CLASS__ (or similar) compiler-defined variable, I've never seen one in any compiler. However, it wouldn't be difficult to define your own for each class:
This only declares the variable, you still need to define it in your implementation file:
I'm prone to making a lot of mistakes, and this is something I'm likely to forget. Fortunately, in this case if you forget to include this in a class, your compiler will let you know. If you use template files for new classes, this is something that would go nicely in those template files.
Since you're using this for file logging, you've probably got some macros that take advantage of this data. In this case, you'll want to use the __CLASS__ variable anywhere. So you might also want to declare a global __CLASS__ variable with the contents "Global scope" or even just an empty string. But be careful, doing this means that your compiler will no longer warn you if you forget to declare __CLASS__ within your class.
Getting back to the __FUNCTION__, I've only been able to get past this missing variable by actually declaring it at the beginning of every single function. This is a very big hassle, and because of this, I only did this for one project. I've never done it since. Instead, I use a logger class that I included recently as a COTD entry, which uses indentation in the log files to help outline the flow of code from function call to function call (see the LOGFUNC macro). This is an optional thing, and I only use it when I need it. This is something you might consider doing, because it's much less hassle.
Response provided by Paul Nettle
This article was originally an entry in flipCode's Ask Midnight, a Question and Answer column with Paul Nettle that's no longer active.