受this的启发,我试图编写使用内部函数的宏,但失败了:
#include <string.h>
// Define a helper macro to get the file name from __FILE__
#define FILENAME_ONLY(file) (strrchr(file, '/') ? strrchr(file, '/') + 1 : file)
// Use the helper macro to create MYFILENAME
#define MYFILENAME FILENAME_ONLY(__FILE__)
// Create __MYFILE__ macro
#define __MYFILE__ "[" MYFILENAME "]"
#include <stdio.h>
int main() {
printf("%s\n", __MYFILE__);
return 0;
}
我得到:
main.cpp:4:80: error: expression cannot be used as a function
#define FILENAME_ONLY(file) (strrchr(file, '/') ? strrchr(file, '/') + 1 : file)
请问我缺少什么?
strrchr
等在运行时执行。诸如 "[" MYFILENAME "]"
之类的字符串文字连接发生在编译时。你不能疯狂地混合两者。
强烈建议在运行时使用函数来执行所有这些操作。
您可以仅以这种方式连接字符串文字。
示例:
printf("%s", "{" "hello" " " "world" "\n");
串联只能发生在编译时。
这样,除了字符串文字之外,你不能使用任何东西。
您的宏扩展为:
printf("%s\n", "[" (strrchr("/app/example.c", '/') ? strrchr("/app/example.c", '/') + 1 : "/app/example.c") "]");
并且它不符合这个标准。