了解如何编译和正确链接多个c ++文件

时间:2017-12-07 17:53:11

标签: c++ ubuntu compilation g++

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

的main.cpp

#include "other.cpp"


int main()
{
     return test();
}

other.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 include和std命名空间放在main.cpp的顶部,other.cpp也无法识别iostream命令(cout,endl)。我认为#include语句只是将c ++文件内容放在#include语句所在的位置。什么是正确的做法,为什么这不起作用? (问题2)

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

1 个答案:

答案 0 :(得分:1)

当你#include一个文件时,你有效地复制/粘贴该文件的内容在include的行。因此,是的,您在程序中包含方法test()两次。

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