C++ pretty functions

Post by Nico Brailovsky @ 2010-06-22 | Permalink | Leave a comment

There are two well known macros from the preprocessor which every macro-sorcer must know. They are __FILE__ and __LINE__. You probably already know about them but anyway, __FILE__ will give you the current file and __LINE__ the current line. Easy, huh?

int main() {
   printf("%s : %i", FILE, LINE);
   return 0;
}

The program above would give you "main.cpp : 3" as a result. There is nothing going on at execution time, it's all preprocesor wizardy. In fact with "g{++/cc} -E" you can even check what the "real" output is (-E means to return the preprocessor output. Keep in mind a lot of stuff will be included from the headers you use).

int main() {
   printf("%s : %i", "main.cpp", 3);
   return 0;
}

Well that's nice and all, but g++ can top this easily:

int main() {
   std::cout << PRETTY_FUNCTION << "n";
   return 0;
}

There are a couple of notable things about this new "pretty function" thing: * 1. It will demangle a function's name * 2. This time it isn't a preprocessor secret thing but a real variable g++ will create.

You can easily use this for better logging functions now (with some macro wizardy, obviously).


In reply to this post, Nicolás Brailovsky » Blog Archive » Cool C++0X features VI: A variadic wrapper commented @ 2011-05-17T09:06:06.000+02:00:

[...] you want to wrap do_something with something else (Remember __PRETTY_FUNCTION__?). This is a solution, the worst one [...]

Original published here.