将问题与“多重定义”联系起来编译错误
我有以下“常量”标头:
/* constants.h */
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#ifndef CONSTANTS_H
#define CONSTANTS_H
const char * kFoo = "foo";
const char * kBar = "bar";
#endif
#ifdef __cplusplus
}
#endif
我在文件 Xc
和 Yc
中 #include
-ing 这个标头。
请注意,我没有将其包含在 Xh
或 Yh
中。
文件Xc
和Yc
被编译成目标文件,这些目标文件被归档到名为libXY.a
的静态库中。
当我在 Zh
中包含 Xh
和 Yh
时,并且当我链接到 libXY.a
时,我无法编译 < code>Zc 没有错误:
/* Z.h */
#include "X.h"
#include "Y.h"
尝试编译 Zc
时出现以下编译错误:
/path/to/libXY.a(X.o):(.data+0x0): multiple definition of `kFoo`
/path/to/libXY.a(Y.o):(.data+0x0): first defined here
/path/to/libXY.a(X.o):(.data+0x8): multiple definition of `kBar`
/path/to/libXY.a(Y.o):(.data+0x8): first defined here
我尝试设置 kFoo
和 kBar
到extern
,但这没有帮助。
当我只包含一次常量时(通过头保护#ifndef CONSTANTS_H
),我将如何解析多个定义?
I have the following "constants" header:
/* constants.h */
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#ifndef CONSTANTS_H
#define CONSTANTS_H
const char * kFoo = "foo";
const char * kBar = "bar";
#endif
#ifdef __cplusplus
}
#endif
I am #include
-ing this header in files X.c
and Y.c
.
Note that I am not including this in X.h
or Y.h
.
The files X.c
and Y.c
get compiled into object files which are archived into a static library called libXY.a
.
When I include X.h
and Y.h
in Z.h
, and when I link to libXY.a
, I cannot compile Z.c
without errors:
/* Z.h */
#include "X.h"
#include "Y.h"
I get the following compilation errors when trying to compile Z.c
:
/path/to/libXY.a(X.o):(.data+0x0): multiple definition of `kFoo`
/path/to/libXY.a(Y.o):(.data+0x0): first defined here
/path/to/libXY.a(X.o):(.data+0x8): multiple definition of `kBar`
/path/to/libXY.a(Y.o):(.data+0x8): first defined here
I have tried setting kFoo
and kBar
to extern
, but that does not help.
How would I resolve multiple definitions, when I am only including the constants once (via the header guard #ifndef CONSTANTS_H
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
constants.h
中:kFoo
的定义将在#include
的constants.h.因此,多个定义会导致链接错误。
asaelr指出的(+1),你可以像这样解决它:
constants.hconstants.c
正如
(注意我也将指针设置为const,这通常是你在这种情况下想要做的)
With this in
constants.h
:a definition for
kFoo
will be emitted in every translation that#include
sconstants.h
. Thus, multiple definitions, which then result in link errors.As asaelr noted (+1), you would solve it like this:
constants.h
constants.c
(note that i also made the pointer const, which is usually what you want to do in this case)
您不应该在头文件中定义变量。在源文件之一中定义它们,并在头文件中声明它们 (
extern
)。(您写道“我已尝试将 kFoo 和 kBar 设置为 extern,但这没有帮助。”我猜您没有在源文件中定义它们)
You should not define variables in header file. define them in one of the source files, and declare them (
extern
) in the header file.(You wrote "I have tried setting kFoo and kBar to extern, but that does not help." I guess that you didn't define them in a source file)