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?
C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function. In the above example, we have declared two char arrays mainly str1 and str2 of size 100 characters.
std::string::append() in C++ This member function appends characters in the end of string. Syntax 1 : Appends the characters of string str. It Throws length_error if the resulting size exceeds the maximum number of characters.
The __FUNCTION__ This macro can return the current function.
Convert by adding an empty string.Just add to int or Integer an empty string "" and you'll get your int as a String. It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String.
__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++
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With