【问题标题】:Understanding how to compile and correctly link multiple c++ files了解如何编译和正确链接多个 c++ 文件
【发布时间】:2017-12-07 17:53:11
【问题描述】:

我想写一个涉及多个c++文件的基本程序,然后从Ubuntu终端用g++编译程序。

main.cpp

#include "other.cpp"


int main()
{
     return test();
}

其他.cpp

#include <iostream>
using namespace std;

int test()
{

     cout<<"Hello" << endl;

     return 0;
}

...然后我运行

g++ main.cpp other.cpp

首先,这不起作用。我收到以下错误:

/tmp/ccXYALau.o: In function `test()':
other.cpp:(.text+0x0): multiple definition of `test()'
/tmp/ccCIj4co.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

即使我显然没有定义 test() 两次? (问题1)

其次,我不得不放

#include <iostream>
using namespace std;

在 other.cpp 中,而不是更有意义的 main.cpp。这是因为出于某种原因,即使我将 iostream 包含和 std 命名空间放在 main.cpp 的顶部,other.cpp 也无法识别 iostream 命令(cout、endl)。我认为#include 语句只是将c++ 文件内容放在#include 语句所在的位置。什么是正确的做法,为什么这不起作用? (问题2)

最后,一般来说,如果我的项目变得更复杂,包含更多文件,如何编译所有文件并链接它们(不应该所有包含在 main.cpp 中)以及编译它们的过程是什么? (问题3)

【问题讨论】:

标签: c++ ubuntu compilation g++


【解决方案1】:

当您#include 一个文件时,您实际上是将该文件的内容复制/粘贴到包含的行。因此,是的,您在程序中包含了两次 test() 方法。

您通常只包含“头”文件。这些通常定义方法的签名。使用 .cpp 文件中方法的主体/实现。

【讨论】:

  • 我什么都明白,除了这种情况下的事实,我怎么把它包括了两次?我在 other.cpp 中定义它,并在 main.cpp 中包含 other.cpp。第二个定义在哪里?
  • 您在 main.cpp 中“嵌入”了 other.cpp,并且您还在编译时将其添加到命令行中。
  • 哦,所以我应该只编译 main.cpp?
  • 您永远不应该包含 .cpp 文件。
  • 是的。这是解决问题的一种方法。
猜你喜欢
  • 1970-01-01
  • 2013-09-04
  • 2020-12-20
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
相关资源
最近更新 更多