This should be trivial but I cannot seem to figure out how to concatenate __FUNCTION__
with strings especially on GCC -- although it works on VC++ (I'm porting some code to Linux)
#include <iostream>
#include <string>
#define KLASS_NAME "Global"
int main()
{
std::string msg = KLASS_NAME "::" __FUNCTION__;
std::cout << msg << std::endl;
}
Online VC++ version
GCC error message
Test.cpp:9:36: error: expected ‘,’ or ‘;’ before ‘__FUNCTION__’
std::string msg = KLASS_NAME "::" __FUNCTION__;
Update
Thanks to Chris, apparently adjacent string literals are concatenated [reference]. So VC++ may be correct in this case, until you consider that __FUNCTION__
is non-standard.
Macro Concatenation with the ## OperatorThe ## (double number sign) operator concatenates two tokens in a macro invocation (text and/or arguments) given in a macro definition. If a macro XY was defined using the following directive: #define XY(x,y) x##y.
Concatenation means joining two strings into one. In the context of macro expansion, concatenation refers to joining two lexical units into one longer one. Specifically, an actual argument to the macro can be concatenated with another actual argument or with fixed text to produce a longer name.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
You need a concatenation operator and explicitly construct the string such that the right concatenation operator is found:
#include <iostream>
#include <string>
#define KLASS_NAME "Global"
int main()
{
std::string msg = std::string(KLASS_NAME) + "::" + __FUNCTION__;
std::cout << msg << std::endl;
}
Live example: http://ideone.com/vn4yra
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