5

Please pardon me if I am asking an obvious question, but after going through a bunch of threads and trying out stuff, I am not able to pin down this simple thing.

I have this small program:

#define FUNC_PREFIX __FUNCTION__ "() :"

int main()
{
    printf("%s\n", FUNC_PREFIX);
    return 0;
}

So I can pass FUNC_PREFIX instead of __FUNCTION__ to log functions and they will print the calling function name followed by paren and colon — just so to improve readability of log line outputs.

This compiles fine as-is in Visual Studio 2008. But in g++, I get an error expected ‘)’ before string constant

I tried a few things like doing:

#define TEMP __FUNCTION__ 
#define FUNC_PREFIX TEMP "() :" 

but to no avail.

What is the way to go about doing this?

1
  • If the logging code knows it is passed a function name, the correct place to add the parentheses and colon is in the logging code. If the logging code doesn't know that it's getting a function name, then you probably need more information than just the function name and can format that to include the parentheses. Note that the accepted answer using #define FUNC_PREFIX __func__,"() :" cannot be used in many places other than a printf-family function. For example, strcpy(buffer, FUNC_PREFIX) won't compile but strcpy(buffer, (FUNC_PREFIX)) will — but it won't do what you want. Feb 12, 2018 at 15:33

2 Answers 2

9

__FUNCTION__ is not a macro in either standard C or standard C++.

Both C++ 2011 (§8.4 Function definitions, and §8.4.1 In general) and C 1999 or 2011 have a pre-defined identifier __func__ which is the name of the function. It is not a macro, so you would not be able to concatenate a string with it in the preprocessor.

So, you will have to revise your code if it is to work with standard-compliant C or C++ compilers that do not support the MSVS extension.


GCC manual (for version 4.6.1) has section §6.47 Function names as strings. It documents that __FUNCTION__ is a synonym for __func__. It also discusses __PRETTY_FUNCTION__. These are not preprocessor macros. So, you will have to adapt your code to work correctly with gcc or g++.

0
1

Your printf is missing a quote. Use identifier __func__ and you can print two strings if you define the macro as:

#define FUNC_PREFIX __func__,"() :"

int main()
{
    printf("%s %s\n", FUNC_PREFIX);
    return 0;
}
1
  • Thanks for pointing out the quote part - had forgotten to include that while posting the question.
    – sskanitk
    Oct 2, 2012 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.