简体   繁体   English

链接具有相同定义的两个目标文件时出现多定义错误

[英]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.cppb.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.cppb.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.

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