链接问题与"&的多个QUOT定义;编译错误 [英] Linking issue with "multiple definition of" compilation error

查看:173
本文介绍了链接问题与"&的多个QUOT定义;编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的常量标题:

  / * * constants.h /#IFDEF __cplusplus
为externC{
#万一曾经的#pragma的#ifndef CONSTANTS_H
#定义CONSTANTS_H为const char * kFoo =富;
为const char *千巴=酒吧;#万一#IFDEF __cplusplus
}
#万一

我是的#include -ing在文件 XC 报头,而 YC

请注意,我的不可以包括本在 XH YH

中的文件 XC YC 编译到它们压缩成一个叫做静态库的目标文件 libXY.a

当我包括 XH YH 深航 ,当我链接到 libXY.a ,我不能编译 ZC 没有错误:

  / * * Z.h /#包括X.h
#包括Y.h

在编译的时候,我得到以下编译错误 Z.c

  /path/to/libXY.a(X.O):(数据+为0x0):kFoo`的'多重定义
/path/to/libXY.a(Y.o):(.data+0x0):首先这里定义
/path/to/libXY.a(X.o):(.data+0x8):`kBar`的多重定义
/path/to/libXY.a(Y.o):(.data+0x8):首先这里定义

我曾尝试 kFoo 千巴设置为的extern ,但这并不能帮助。

如何将解决多个定义,当我只包括一次常数(通过头文件保护的#ifndef CONSTANTS_H )?


解决方案

  我

如何将解决多个定义,当我只有(通过头文件保护的#ifndef CONSTANTS_H),包括曾经的常量?


有了这个 constants.h

 为const char * kFoo =富;

kFoo 的定义会在每一个的#include 取值常量翻译发射.H 。因此,多个定义,然后导致链接错误。

由于asaelr指出的(+1),你会解决这个问题是这样的:

constants.h

 的extern为const char * const的kFoo;

constants.c

 为const char * const的kFoo =富;

(请注意,我也做了指针常量,这是的一般的你想在这种情况下做什么)

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)?

解决方案

How would I resolve multiple definitions, when I am only including the constants once (via the header guard #ifndef CONSTANTS_H)?

With this in constants.h:

const char * kFoo = "foo";

a definition for kFoo will be emitted in every translation that #includes constants.h. Thus, multiple definitions, which then result in link errors.

As asaelr noted (+1), you would solve it like this:

constants.h

extern const char* const kFoo;

constants.c

const char* const kFoo = "foo";

(note that i also made the pointer const, which is usually what you want to do in this case)

这篇关于链接问题与"&的多个QUOT定义;编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆