“某事”的多重定义

发布于 2024-11-30 13:06:29 字数 437 浏览 1 评论 0原文

在“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紧拥背影 2024-12-07 13:06:29

一如既往,不要在头文件中定义变量。因为每次你#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.

神妖 2024-12-07 13:06:29

您应该创建一个新文件 (my_stuff.c),并在其中包含以下内容:

char *logfile = "my_output.txt";

.c 文件定义变量。然后更改标头以使用此内容而不是定义:

extern char *logfile;

这使其成为声明。现在一切应该可以工作了,但是您必须编译额外的模块,并将其包含在链接阶段。 (具体操作取决于您的开发工具。)

You should create a new file (my_stuff.c), and have this in there:

char *logfile = "my_output.txt";

The .c file defines the variable. Then change the header to have this instead of the definition:

extern char *logfile;

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文