7

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.

11
  • What's your error with gcc? Commented Mar 30, 2017 at 11:15
  • It's worth noting that __FUNCTION__ isn't standard and that __func__ isn't a string literal. Commented Mar 30, 2017 at 11:16
  • 1
    use stringizing operator '##' #define cocat(a,b) a##b Commented Mar 30, 2017 at 11:16
  • @AliAkberFaiz, That's the concatenation operator and it's required to produce a valid token. Commented Mar 30, 2017 at 11:17
  • Why one earth does VC++ even accept KLASS_NAME "::" __FUNCTION__ if its not valid? I'm assuming its not. Commented Mar 30, 2017 at 11:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.