简体   繁体   中英

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++.

main.cpp

#include "other.cpp"


int main()
{
     return test();
}

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? (question 1)

Secondly, I had to put

#include <iostream>
using namespace std;

in other.cpp, instead of what would make more sense, 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). I thought #include statements just put the c++ file contents where the #include statement is. What is the correct thing to do, and why does this not work? (question 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? (question 3)

When you #include a file you effectively copy/paste the contents of that file at the line of the include. Therefore, yes, you are including the method test() twice in your program.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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