[英]Understanding how to compile and correctly link multiple c++ files
我想編寫一個涉及多個c ++文件的基本程序,然后使用g ++從Ubuntu終端編譯該程序。
#include "other.cpp"
int main()
{
return test();
}
#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 namepacing放在main.cpp的頂部時,other.cpp也無法識別iostream命令(cout,endl)。 我認為#include語句只是將c ++文件內容放在#include語句所在的位置。 正確的做法是什么,為什么這不起作用? (問題2)
最后,總的來說,如果我的項目變得越來越復雜,包含了更多文件,那么如何編譯所有文件並將它們鏈接起來(不是所有包含的文件都在main.cpp中),編譯它們的過程是什么? (問題3)
#include文件時,您可以有效地復制/粘貼該文件的內容到include行。 因此,是的,您在程序中兩次包含了方法test()。
通常,您僅包括“頭”文件。 這些通常定義方法的簽名。 .cpp文件中方法的主體/實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.