在 CentOS 上写 C++ 程序,一般流程是:安装编译环境 → 写代码 → 编译 → 运行。下面按步骤说明,适合新手。
sudo yum update -y
sudo yum install -y gcc gcc-c++
g++ --version
看到版本号说明安装成功。
vim hello.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, CentOS C++!" << endl;
return 0;
}
保存并退出(:wq)。
g++ hello.cpp -o hello
hello.cpp:源文件-o hello:生成可执行文件 hello./hello
输出:
Hello, CentOS C++!
g++ -Wall hello.cpp -o hello
g++ -std=c++11 hello.cpp -o hello
g++ -std=c++17 hello.cpp -o hello
g++ -g hello.cpp -o hello
Makefileall:
g++ -std=c++17 hello.cpp -o hello
clean:
rm -f hello
make
./hello
make clean
| 工具 | 说明 |
|---|---|
| vim | 轻量终端编辑器 |
| nano | 更简单 |
| VS Code | 远程 SSH 开发 |
| CLion | 专业 C++ IDE |
g++: command not found没安装 gcc-c++:
sudo yum install gcc-c++
chmod +x hello
如果你愿意,我可以:
你现在用的是 CentOS 7 还是 CentOS 8/Stream?