【发布时间】: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)
【问题讨论】:
-
使用头文件。
-
我认为 .cpp 和 .h 之间没有实际区别。或者这真的只是考虑到他们都执行 c++ 代码的事实吗?
-
源文件和头文件按照约定是不同的。它们有不同的功能。
标签: c++ ubuntu compilation g++