gpt4 book ai didi

C++ 在 Windows 中编译,在 Linux 中出现多重定义错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:42 25 4
gpt4 key购买 nike

首先让我说我不是最好的 C++,而且我对 Linux 知之甚少。对于一个类项目,我们必须实现一个堆,所以我在我的 Windows PC 上编写了所有代码,假设我可以将文件上传到学校拥有的 Linux 存储库。 [也许这是我出错的地方,这不能简单地完成。] 我的代码编译并清除了我的 Windows 电脑上提供的所有测试用例。当我将文件上传到 Linux 时,我创建了一个 makefile,当我使用 make 命令时,我得到了一个包含多个定义错误的 list 。我使用的每个函数一个错误。我做了一些搜索,但比开始时更加困惑。

我的文件是:main.cpp、main.h、heap.cpp、heap.h、util.cpp 和 util.h。

我认为问题出在我的 include 语句上,但我不是 100% 确定。

这是文件的示例。

主要.cpp

 #include <iostream>  //needed to use basic inputs/outputs
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#include "util.cpp"
#include "heap.cpp"
#include <fstream>
using namespace std;

main.h 是空白的。

堆.cpp

 #include <iostream>  //needed to use basic inputs/outputs
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
#include <cmath>
#include <math.h>
using namespace std;

//expanded functions found in the heap.h file

堆.h

 //2 structs
//9 functions

工具.cpp

 #include <iostream>  //needed to use basic inputs/outputs
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
using namespace std;

//expanded functions found in util.h

工具.h

 //1 function

在 heap.h 和 util.h 之间,我有 10 个函数,在运行 make 命令时,我收到关于所有 10 个的警告:

 multiple definition of 'FUNCTIONNAME'
main.o:main.cpp:(.text+0x1b7): first defined here

我假设 0x1b7 是一个内存位置,因为它们各不相同。

如有任何帮助,我们将不胜感激。

最佳答案

您没有显示 Makefile,但很可能,它包含此规则或类似规则

program: main.o heap.o util.o
$(CXX) $(CXXFLAGS) -o program main.o heap.o util.o

现在发生了什么,编译器构建了三个目标文件 main.o、heap.o 和 util.o。接下来将目标文件链接在一起以构建程序

链接器会看到分别在 main.o 和 heap.o 或 main.o 和 util.o 中定义的各种函数的定义。这就是为什么它提示“‘FUNCTIONNAME’的多重定义”


为什么这些函数定义了不止一次?

当您将文件包含到另一个源中时,就好像您复制了 #include 位置的内容。这意味着在 heap.cpp 中定义了一个函数:

void create_heap(int size)
{
// create a heap ...
}

被逐字复制到 main.cpp 中,其中行

#include "heap.cpp"

是。


因为 heap.cpp 有 create_heap() 的定义,而 main.cpp #include 是 heap.cpp 的内容,两者都包含自己的 创建堆()。现在编译 heap.o 和 main.o,并将它们链接在一起。每个目标文件都有一个 create_heap() 的拷贝,这就是链接器感到困惑和提示的地方

multiple definition of 'create_heap'
main.o:main.cpp:(.text+0x1b7): first defined here

要解决此问题,只需替换包含 cpp 源的行,例如

#include "util.cpp"
#include "heap.cpp"

各自的头文件

#include "util.h"
#include "heap.h"

只保留与main.cpp相关的函数定义,除此之外别无其他。现在 main.cpp 没有属于 util.cpp 或 heap.cpp 的函数定义,链接器错误也消失了。


据推测,这在 Windows 上有效,因为只有 main.cpp 包含在项目文件中,因此在生成的可执行文件中只有一个定义(来自 main.o)。

如果您在 Linux Makefile 中包含了所有源代码,那么该错误也可能在 Windows 中出现。

关于C++ 在 Windows 中编译,在 Linux 中出现多重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com