Next: , Previous: Incomplete Enums, Up: C Extensions



5.44 Function Names as Strings

GCC predefines two magic identifiers to hold the name of the current function. The identifier __FUNCTION__ holds the name of the function as it appears in the source. The identifier __PRETTY_FUNCTION__ holds the name of the function pretty printed in a language specific fashion.

These names are always the same in a C function, but in a C++ function they may be different. For example, this program:

     extern "C" {
     extern int printf (char *, ...);
     }
     
     class a {
      public:
       sub (int i)
         {
           printf ("__FUNCTION__ = %s\n", __FUNCTION__);
           printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
         }
     };
     
     int
     main (void)
     {
       a ax;
       ax.sub (0);
       return 0;
     }

gives this output:

     __FUNCTION__ = sub
     __PRETTY_FUNCTION__ = int  a::sub (int)

The compiler automagically replaces the identifiers with a string literal containing the appropriate name. Thus, they are neither preprocessor macros, like __FILE__ and __LINE__, nor variables. This means that they catenate with other string literals, and that they can be used to initialize char arrays. For example

     char here[] = "Function " __FUNCTION__ " in " __FILE__;

On the other hand, #ifdef __FUNCTION__ does not have any special meaning inside a function, since the preprocessor does not do anything special with the identifier __FUNCTION__.

Note that these semantics are deprecated, and that GCC 3.2 will handle __FUNCTION__ and __PRETTY_FUNCTION__ the same way as __func__. __func__ is defined by the ISO standard C99:

     The identifier __func__ is implicitly declared by the translator
     as if, immediately following the opening brace of each function
     definition, the declaration
     
          static const char __func__[] = "function-name";
     

appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.

By this definition, __func__ is a variable, not a string literal. In particular, __func__ does not catenate with other string literals.

In C++, __FUNCTION__ and __PRETTY_FUNCTION__ are variables, declared in the same way as __func__.