我有以下“常量”标题:
/* 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),我将如何解决多个定义?
解决方法
How would I resolve multiple definitions,when I am only including the constants once (via the header guard #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,这通常是你想要做的事情)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。