Nicolás Brailovsky


A modern blog

C++ pretty functions

author Posted by: nico on date Jun 22nd, 2010 | filed Filed under: C++

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?

  1. int main() {
  2.    printf("%s : %i", __FILE__, __LINE__);
  3.    return 0;
  4. }
gccegg-65

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).

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

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

  1. int main() {
  2.    std::cout << __PRETTY_FUNCTION__ << "\n";
  3.    return 0;
  4. }

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).

tagOne Response to “C++ pretty functions”

  1. Nicolás Brailovsky » Blog Archive » Cool C++0X features VI: A variadic wrapper Said,

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

     Add A Comment

trackback Trackback URI | rsscomment Comments RSS