链接问题与“多重定义”编译错误
我有以下“常量”标题:
/* 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 我在文件X.c和Y.c中包含了这个标题. 请注意,我不在X.h或Y.h中包含它. 文件X.c和Y.c被编译成目标文件,这些文件存档到名为libXY.a的静态库中. 当我在Z.h中包含X.h和Y.h时,当我链接到libXY.a时,我无法编译Z.c而没有错误: /* Z.h */ #include "X.h" #include "Y.h" 尝试编译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 我已经尝试将kFoo和kBar设置为extern,但这没有用. 当我只包含常量一次时(通过标题保护#ifndef CONSTANTS_H),我将如何解决多个定义? 解决方法
在constants.h中使用它: const char * kFoo = "foo"; 在#includes constants.h的每个翻译中都会发出kFoo的定义.因此,多个定义,然后导致链接错误. 正如asaelr指出的那样(1),你可以这样解决: constants.h extern const char* const kFoo; constants.c const char* const kFoo = "foo"; (注意我也做了指针const,这通常是你想要做的事情) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |