简体   繁体   English

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

[英]Understanding how to compile and correctly link multiple c++ files

I want to write a basic program that involves multiple c++ files, and then compile the program from Ubuntu terminal with g++. 我想编写一个涉及多个c ++文件的基本程序,然后使用g ++从Ubuntu终端编译该程序。

main.cpp main.cpp中

#include "other.cpp"


int main()
{
     return test();
}

other.cpp other.cpp

#include <iostream>
using namespace std;

int test()
{

     cout<<"Hello" << endl;

     return 0;
}

...and then I run ...然后我跑

g++ main.cpp other.cpp

Firstly, this does not work. 首先,这不起作用。 I get the following error: 我收到以下错误:

/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

Even though I am clearly not defining test() twice? 即使我显然没有两次定义test()? (question 1) (问题1)

Secondly, I had to put 其次,我不得不把

#include <iostream>
using namespace std;

in other.cpp, instead of what would make more sense, main.cpp. 在other.cpp中,main.cpp代替了更有意义的选择。 This is because for some reason, even when I put the iostream include and the std namespacing at the top of main.cpp, other.cpp did not recognise iostream commands (cout, endl). 这是因为由于某些原因,即使当我将iostream include和std namepacing放在main.cpp的顶部时,other.cpp也无法识别iostream命令(cout,endl)。 I thought #include statements just put the c++ file contents where the #include statement is. 我认为#include语句只是将c ++文件内容放在#include语句所在的位置。 What is the correct thing to do, and why does this not work? 正确的做法是什么,为什么这不起作用? (question 2) (问题2)

Finally, in general if my project gets more complex with more files, how does compiling all of them and linking them work (shouldn't all the includes be in main.cpp) and what is the process to compile them? 最后,总的来说,如果我的项目变得越来越复杂,包含了更多文件,那么如何编译所有文件并将它们链接起来(不是所有包含的文件都在main.cpp中),编译它们的过程是什么? (question 3) (问题3)

When you #include a file you effectively copy/paste the contents of that file at the line of the include. #include文件时,您可以有效地复制/粘贴该文件的内容到include行。 Therefore, yes, you are including the method test() twice in your program. 因此,是的,您在程序中两次包含了方法test()。

You generally only include "header" files. 通常,您仅包括“头”文件。 These generally define the signature of the methods. 这些通常定义方法的签名。 With the body/implementation of the method in the .cpp file. .cpp文件中方法的主体/实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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