问题
Isn't __FUNCTION__
a string literal? I'd always thought it was - along the lines of __FILE__
, but I just discovered I can't adjacently concatenate a string literal to it. If it's not a string literal, what is it defined as? I can't get cscope to resolve it.
E.g.
#include <iostream>
int main( int argc, char* argv[] )
{
std::cout << __FILE__ << std::endl;
std::cout << __FILE__ "A" << std::endl;
std::cout << __FUNCTION__ << std::endl;
//std::cout << __FUNCTION__ "A" << std::endl; // Doesn't compile.
return 0;
}
The error when the problem line is included:
>g++ --version
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
>g++ -g main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:8:29: error: expected ';' before string constant
std::cout << __FUNCTION__ "A" << std::endl; // Doesn't compile.
回答1:
Isn't
__FUNCTION__
a string literal?
No.
From https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Function-Names.html
These identifiers are variables, not preprocessor macros, and may not be used to initialize char arrays or be concatenated with string literals.
回答2:
Short answer, no, __FUNCTION__
is not a string literal, it's a pointer to a const char *
variable containing the name of the function.
Because the __FUNCTION__
macro doesn't expand directly to the function name, instead, it expands to something like this (the exact name is probably different, but the name is stores as a pointer to char*):
const char *func_name = "main";
std::cout << func_name << std::endl;
And of course, if you have that code, it's quite easy to see that:
std::cout << func_name "A" << std::endl;
will not compile.
来源:https://stackoverflow.com/questions/48124994/why-cant-a-string-literal-be-concatenated-to-function