任何人都可以告诉g ++何时__FUNCTION__用包含函数名称的字符串替换'macro'?它似乎可以替换它,直到它检查源代码的语法正确性,即以下将不起作用
#include <whatsneeded>
#define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__
int main(int argc, char* argv)
{
printf(DBG_WHEREAMI "\n"); //*
}
Run Code Online (Sandbox Code Playgroud)
因为经过预处理后使用
g++ -E test.cc
Run Code Online (Sandbox Code Playgroud)
来源看起来像
[...]
int main(int argc, char* argv)
{
printf(__FUNCTION__ "test.cc" "6" "\n"); //*
}
Run Code Online (Sandbox Code Playgroud)
现在编译器正确抛出,因为*ed行不正确.
有没有办法强制用字符串替换前一步,以便该行正确?
难道__FUNCTION__真的毕竟是一个字符串替换?或者它是编译代码中的变量?
我正在使用C/Objective-C开发一个应用程序(请不要使用C++,我已经有了解决方案),我遇到了一个有趣的用例.
因为clang不支持嵌套函数,所以我的原始方法不起作用:
#define CREATE_STATIC_VAR(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
Run Code Online (Sandbox Code Playgroud)
这段代码可以用GCC编译好,但由于clang不支持嵌套函数,我得到一个编译错误:
预期';' 在宣言结束时.
所以,我找到了一个适用于Clang函数内部变量的解决方案:
#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage
Run Code Online (Sandbox Code Playgroud)
但是,我想知道是否有办法利用宏连接来为情况选择合适的方法,例如:
#define CREATE_STATIC_VAR_GLOBAL(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
#define CREATE_STATIC_VAR_LOCAL(Type, Name, …Run Code Online (Sandbox Code Playgroud) scope global-variables static-variables clang nested-function