"某事"的多重定义

mah*_*ood -1 c multiple-definition-error

在"my_header.h"中我定义了

FILE *f;
char *logfile = "my_output.txt";
#define OPEN_LOG     f = fopen(logfile, "a")
#define CLOSE_LOG    fclose(f)
Run Code Online (Sandbox Code Playgroud)

在"my_source.c"中,我以这种方式使用它

#include "my_header.h"
....
OPEN_LOG;
fprintf(f, "some strings\n");
CLOSE_LOG;
Run Code Online (Sandbox Code Playgroud)

然而链接器说

my_source.o:(.data+0x0): multiple definition of `logfile'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Oli*_*rth 5

与往常一样,不要在头文件中定义变量.因为每次你的#include头文件,该变量将被重新定义(记住#include=="复制和粘贴",有效),导致你看到的链接器错误.