在 CentOS 上写并运行 C++ 代码,一般步骤如下:
CentOS 默认可能没有 g++,先检查:
g++ --version
如果没有,安装:
sudo yum install gcc gcc-c++ -y
(CentOS 8 可用 dnf)
用 vim 或 nano 创建一个文件:
vim hello.cpp
内容示例:
#include <iostream>
using namespace std;
int main() {
cout << "Hello CentOS C++" << endl;
return 0;
}
保存退出(vim 中按 Esc,输入 :wq)。
g++ hello.cpp -o hello
hello.cpp:源文件-o hello:生成可执行文件 hello./hello
输出:
Hello CentOS C++
g++ -std=c++11 hello.cpp -o hello # 指定 C++ 标准
g++ -Wall hello.cpp -o hello # 显示警告
g++ -O2 hello.cpp -o hello # 优化
g++ main.cpp func.cpp -o app
Makefile 示例:
app: main.cpp func.cpp
g++ main.cpp func.cpp -o app
clean:
rm -f app
使用:
make
./app
make clean
如果你是想:
可以告诉我,我可以一步步教你。