【发布时间】:2019-12-29 06:26:41
【问题描述】:
我正在尝试创建一个日志函数,该函数将采用日志类型 msg 并将添加文件名、函数名、调用日志函数的行。我创建了以下测试代码,但出现了我不理解的错误
#include<stdio.h>
#define func(type, msg, ...) func(type, __FILE__, __func__, __LINE__, msg, __VA_ARGS__)
void func(int type, const char *file, const char *function, int line, const
char *msg, ...)
{
printf("%s",msg);
}
main()
{
func(10,"time");
}
这里是错误日志:
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
E:\code\C code\A.c|6|error: expected declaration specifiers or '...' before string constant|
E:\code\C code\A.c|3|error: expected declaration specifiers or '...' before '__func__'|
E:\code\C code\A.c|6|note: in expansion of macro 'func'|
E:\code\C code\A.c|6|error: expected declaration specifiers or '...' before numeric constant|
E:\code\C code\A.c|6|warning: type defaults to 'int' in declaration of 'msg' [-Wimplicit-int]|
E:\code\C code\A.c|3|note: in definition of macro 'func'|
E:\code\C code\A.c|12|warning: return type defaults to 'int' [-Wimplicit-int]|
E:\code\C code\A.c||In function 'main':|
E:\code\C code\A.c|3|warning: implicit declaration of function 'func' [-Wimplicit-function-
declaration]|
E:\code\C code\A.c|15|note: in expansion of macro 'func'|
E:\code\C code\A.c|3|error: expected expression before ')' token|
E:\code\C code\A.c|15|note: in expansion of macro 'func'|
||=== Build failed: 4 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
我已阅读此question,但无法将解决方案与我的代码联系起来。
【问题讨论】:
-
函数名
func替换为您的定义。 -
const *msg->const char *msg -
将 char *func 更改为 char *fnc 后错误仍然存在
-
FILE是<stdio.h>中的一个类型(或者,至少,FILE *是)。那可能会把事情扔掉。我建议你应该在函数中使用const char *file(添加const并重命名它。为了一致性,也将LINE重命名为小写line。 -
建议将
void func(int type, char *FILE, char *fnc, int LINE, const cahr *msg, ...)替换为void (func)(int type, const char *file, const char *function, int line, const char *msg, ...)。func周围的括号防止它被视为宏的调用。我会使用function而不是fnc,但是YMMV。我也可能将msg重命名为fmt— 看起来它可能是printf()系列函数之一的格式字符串(实际上是vprintf()系列之一)。而且我可能会为函数使用一个比func更有意义的名称。
标签: c gcc compiler-errors macros