(用一个C++ Primer Plus里的例子好了)
- 编写C++文件,储存为test1.cpp
//-------------ubuntu上.cpp文件编译与运行
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize);
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
- 终端中输入
xxxx@xxxx-xxxxxx-xxxxxxx-xxxxx:~/文档/cppfile$ g++ test1.cpp
同目录下生成一个a.out文件
xxxx@xxxx-xxxxxx-xxxxxxx-xxxxx:~/文档/cppfile$ ls
a.out test1.cpp
- 终端中输入
xxxx@xxxx-xxxxxx-xxxxxxx-xxxxx:~/文档/cppfile$ ./a.out
Enter your name:
Rawa
Enter your favorite dessert:
Cake
I have some delicious Cake for you, Rawa.
编译运行成功
由于只编译一个源文件,所以默认情况下自动删除了test1.o文件,若新编译另一个cpp代码,生成的a.out会覆盖原有文件
若同时编译多个源代码文件,则编译器不删除目标代码文件
- 编译多个文件,在终端输入
xxxx@xxxx-xxxxxx-xxxxxxx-xxxxx:~/文档/cppfile$ g++ testH.h test2.cpp
xxxx@xxxx-xxxxxx-xxxxxxx-xxxxx:~/文档/cppfile$ ./a.out
This is your Pokemon! Try to talk to it.
Hello Pikachu!
Pikapika !
Pikachu ! ! !
编译运行成功