Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does #ifndef __func__ return true?

Tags:

c++

func

The following code,

#include <iostream>

#ifndef __func__
#   ifdef __FUNCTION__
#       define __func__ __FUNCTION__
#   else
//#       error This compiler supports neither __func__ nor __FUNCTION__
#   endif
#endif


int main(int argc, char **argv)
{
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
}

gives the following expected output,

main
main
int main(int, char**)

However, if I uncomment the else condition, compilation fails because neither __func__ nor __FUNCTION__ are defined. How can this be? They clearly are defined as seen in the output above. Is there some simple principle regarding #ifdef/#ifndef that I'm missing here?

like image 741
Southern.Cross Avatar asked Apr 17 '26 19:04

Southern.Cross


1 Answers

__func__ is not a macro. It is a magic variable, as are __FUNCTION__ and __PRETTY_FUNCTION__.

From https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Function-Names.html:

GCC provides three magic variables that hold the name of the current function, as a string. The first of these is __func__, which is part of the C99 standard:

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";

...

__FUNCTION__ is another name for __func__.

...

In C, __PRETTY_FUNCTION__ is yet another name for __func__. However, in C++, __PRETTY_FUNCTION__ contains the type signature of the function as well as its bare name.

like image 103
R Sahu Avatar answered Apr 20 '26 09:04

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!