简体   繁体   English

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

[英]Linking issue with “multiple definition of” compilation error

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 Xc and Yc . 我在文件XcYc #include -ing这个标题。

Note that I am not including this in Xh or Yh . 请注意,我不是XhYh包含它。

The files Xc and Yc get compiled into object files which are archived into a static library called libXY.a . 文件XcYc被编译成目标文件,这些目标文件存档到名为libXY.a的静态库中。

When I include Xh and Yh in Zh , and when I link to libXY.a , I cannot compile Zc without errors: 当我在Zh包含XhYh时,当我链接到libXY.a ,我无法编译Zc而没有错误:

/* Z.h */

#include "X.h"
#include "Y.h"

I get the following compilation errors when trying to compile Zc : 尝试编译Zc时出现以下编译错误:

/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. 我已经尝试将kFookBar设置为extern ,但这没有用。

How would I resolve multiple definitions, when I am only including the constants once (via the header guard #ifndef CONSTANTS_H )? 当我只包含常量一次时(通过标题保护#ifndef CONSTANTS_H ),我将如何解决多个定义?

How would I resolve multiple definitions, when I am only including the constants once (via the header guard #ifndef CONSTANTS_H)? 当我只包含常量一次时(通过标题保护#ifndef CONSTANTS_H),我将如何解决多个定义?

With this in constants.h : constants.h使用它:

const char * kFoo = "foo";

a definition for kFoo will be emitted in every translation that #include s constants.h . #include s constants.h每个翻译中都会发出kFoo的定义。 Thus, multiple definitions, which then result in link errors. 因此,多个定义,然后导致链接错误。

As asaelr noted (+1), you would solve it like this: 正如asaelr所说(+1),你会这样解决:

constants.h constants.h

extern const char* const kFoo;

constants.c 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) (注意我也做了指针const,这通常是你想要做的事情)

You should not define variables in header file. 您不应该在头文件中定义变量。 define them in one of the source files, and declare them ( extern ) in the header file. 在其中一个源文件中定义它们,并在头文件中声明它们( extern )。

(You wrote "I have tried setting kFoo and kBar to extern, but that does not help." I guess that you didn't define them in a source file) (您写道“我已尝试将kFoo和kBar设置为extern,但这没有帮助。”我猜您没有在源文件中定义它们)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM