链接问题与“多重定义”编译错误
我有以下“常量”标题:
/* 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
,我无法编译Zc
而没有错误:
/* Zh */ #include "Xh" #include "Yh"
尝试编译Zc
时出现以下编译错误:
/path/to/libXY.a(Xo):(.data+0x0): multiple definition of `kFoo` /path/to/libXY.a(Yo):(.data+0x0): first defined here /path/to/libXY.a(Xo):(.data+0x8): multiple definition of `kBar` /path/to/libXY.a(Yo):(.data+0x8): first defined here
我已经尝试将kFoo
和kBar
设置为extern
,但这没有用。
当我只包含常量一次时(通过标题保护#ifndef CONSTANTS_H
),我将如何解析多个定义?
当我只包含常量一次时(通过标题保护#ifndef CONSTANTS_H),我将如何解析多个定义?
在constants.h
使用它:
const char * kFoo = "foo";
在#include
s constants.h
每个翻译中都会发出kFoo
的定义。 因此,多个定义,然后导致链接错误。
正如asaelr所说(+1),你会这样解决:
constants.h
extern const char* const kFoo;
constants.c
const char* const kFoo = "foo";
(注意我也做了指针const,这通常是你想要做的事情)
您不应该在头文件中定义变量。 在其中一个源文件中定义它们,并在头文件中声明它们( extern
)。
(您写道“我已尝试将kFoo和kBar设置为extern,但这没有帮助。”我猜您没有在源文件中定义它们)