c++stringg++c-preprocessor

g++ __FUNCTION__ replace time


Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work

#include <whatsneeded>
#define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__

int main(int argc, char* argv)
{
  printf(DBG_WHEREAMI "\n"); //*
}

since after preprocessing using

g++ -E test.cc

the source looks like

[...]

int main(int argc, char* argv)
{
  printf(__FUNCTION__ "test.cc" "6" "\n"); //*
}

and now the compiler rightly throws up because the *ed line is incorrect.

Is there any way to force that replacement with a string to an earlier step so that the line is correct?

Is __FUNCTION__ really replaced with a string after all? Or is it a variable in the compiled code?


Solution

  • Is there any way to force that replacement with a string to an earlier step so that the line is correct?

    No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions.

    On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__.

    This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality.