Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating proprocessor macro __FUNCTION__ with a string

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.

like image 996
Olumide Avatar asked Mar 30 '17 11:03

Olumide


People also ask

What is macro concatenation in C?

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.

What is concatenation of macro parameters?

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.

How do you combine two strings?

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.

What is concatenation operator in C?

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.


1 Answers

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

like image 121
Beginner Avatar answered Sep 27 '22 23:09

Beginner