加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

链接问题与“多重定义”编译错误

发布时间:2020-12-16 07:49:22 所属栏目:百科 来源:网络整理
导读:我有以下“常量”标题: /* constants.h */#ifdef __cplusplus extern "C" {#endif#pragma once#ifndef CONSTANTS_H#define CONSTANTS_Hconst char * kFoo = "foo";const char * kBar = "bar";#endif#ifdef __cplusplus}#endif 我在文件X.c和Y.c中包含了这个
我有以下“常量”标题:
/* 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,这通常是你想要做的事情)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读