“某事”的多重定义
在“my_header.h”中我定义了
FILE *f;
char *logfile = "my_output.txt";
#define OPEN_LOG f = fopen(logfile, "a")
#define CLOSE_LOG fclose(f)
,在“my_source.c”中,我以这种方式使用它
#include "my_header.h"
....
OPEN_LOG;
fprintf(f, "some strings\n");
CLOSE_LOG;
但是链接器说
my_source.o:(.data+0x0): multiple definition of `logfile'
How can I fix that?
In "my_header.h" I defined
FILE *f;
char *logfile = "my_output.txt";
#define OPEN_LOG f = fopen(logfile, "a")
#define CLOSE_LOG fclose(f)
and in "my_source.c", I used it in this way
#include "my_header.h"
....
OPEN_LOG;
fprintf(f, "some strings\n");
CLOSE_LOG;
However the linker says
my_source.o:(.data+0x0): multiple definition of `logfile'
How can I fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一如既往,不要在头文件中定义变量。因为每次你
#include
该头文件时,该变量都会被重新定义(记住#include
==“有效地复制和粘贴”),导致您看到的链接器错误。As always, don't define variables in your header file. Because every time you
#include
that header file, that variable will be re-defined (remember that#include
== "copy and paste", effectively), leading to the linker error that you're seeing.您应该创建一个新文件 (
my_stuff.c
),并在其中包含以下内容:.c 文件定义变量。然后更改标头以使用此内容而不是定义:
这使其成为声明。现在一切应该可以工作了,但是您必须编译额外的模块,并将其包含在链接阶段。 (具体操作取决于您的开发工具。)
You should create a new file (
my_stuff.c
), and have this in there:The .c file defines the variable. Then change the header to have this instead of the definition:
This makes it a declaration. Now things should work, but you have to compile the extra module, and include it in the link phase. (Details of doing that depend on your development tools.)