[英]Multiple definition error while linking two object files with same definition
Basically my prob is this : 基本上我的概率是这样的:
I have a header file - foo.h
with a structure pointer human *person = NULL
in it. 我有一个头文件
foo.h
其中有一个结构指针human *person = NULL
。 The definition for structure human
is in another header included within foo.h . 对
human
的结构定义位于foo.h中包含的另一个标头中。 I am creating a shared object file game.so
using foo.h
and few other headers and cpps. 我正在使用
foo.h
和其他一些头文件和cpps创建共享对象文件game.so
Now , I have two different cpp files - a.cpp
and b.cpp
which include the header foo.h. 现在,我有两个不同的cpp文件
a.cpp
和b.cpp
,其中包含标头foo.h。 I am creating an object file ao
separately and bo
separately. 我分别创建目标文件
ao
和分别创建bo
。 I am linking both the object file and game.so
for creating another shared object file tennis.so
and while doing so , am getting multiple definition for the "person". 我同时链接了目标文件和
game.so
以创建另一个共享的目标文件tennis.so
,同时这样做为“人”获取了多个定义。 I am aware that the multiple definition error is because ao
contains the structure definition for person
, so does bo
. 我知道多定义错误是因为
ao
包含person
的结构定义, bo
也是如此。
I have used #pragma once
in foo.h
already. 我已经在
foo.h
使用#pragma once
。 ao
is getting compiled separately and bo
is getting compiled separately. ao
正在分别编译,而bo
正在单独编译。 so i dont think #pragma once or ifdef will be useful here because both a.cpp
and b.cpp
includes foo.h
所以我认为#pragma一次或ifdef在这里都不会有用,因为
a.cpp
和b.cpp
包含foo.h
I cant change the structure defintion in foo.
我无法更改
foo.
的结构定义foo.
h to any other cpp file due to some dependencies while creating game.so
由于创建
game.so
某些依赖性,因此将h转移到任何其他cpp文件
Is there any other way to resolve the multiple definition error I get while creating tennis.so
? 还有什么其他方法可以解决我在创建
tennis.so
的多定义错误?
You need to make sure the person
variable is only defined once. 您需要确保
person
变量仅定义一次。 To do that, you need to only declare that variable in foo.h
: 为此,您只需要在
foo.h
声明该变量:
extern human *person;
Then, in foo.cpp
, you define it: 然后,在
foo.cpp
定义它:
human *person = NULL;
You then include foo.o
in the object files that make up game.so
. 然后,将
foo.o
包含在组成game.so
的目标文件中。
You appear to be confusing DECLARATION with DEFINITION. 您似乎将DECLARATION与DEFINITION混淆了。 Your header should DECLARE the structure, your C/C++ will then use such declaration to define variables or refer to instances of such definition[s].
您的标头应声明结构,然后您的C / C ++将使用此类声明来定义变量或引用此类定义的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.