Adding a line in __FUNCTION__ to a macro

Please forgive me if I ask the obvious question, but after going through a bunch of threads and trying things out, I canโ€™t attach this simple thing.

I have this little program:

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

So I can pass FUNC_PREFIX instead of __FUNCTION__ to the log functions, and they will print the name of the calling function, followed by a pair and a colon, only to improve readability of the output lines of the log.

This compiles as it is in Visual Studio 2008. But in g++ , I get the expected error) before the string constant

I tried several things how to do:

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

but to no avail.

How can this be done?

+4
source share
2 answers

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

 #define FUNC_PREFIX __func__,"() :" int main() { printf("%s %s\n", FUNC_PREFIX); return 0; } 
+2
source

__FUNCTION__ not a macro in 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 predefined identifier __func__ , which is the name of the function. This is not a macro, so you cannot concatenate a string with it in the preprocessor.

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


The GCC manual (for version 4.6.1) has a section ยง6.47 Function names as strings. It documents that __FUNCTION__ is synonymous with __func__ . It also discusses __PRETTY_FUNCTION__ . These are not preprocessor macros. So, you will need to properly configure your code using gcc or g++ .

+7
source

Source: https://habr.com/ru/post/1437468/


All Articles