温馨提示×

centos如何编译c++程序

小樊
48
2026-09-09 00:44:39
栏目: 编程语言

在 CentOS 上编译 C++ 程序,通常步骤如下:


一、检查/安装编译器(g++)

CentOS 默认可能没装 g++,先检查:

g++ --version

如果提示 command not found,安装:

CentOS 7

sudo yum install gcc-c++

CentOS 8 / Stream

sudo dnf install gcc-c++

安装完成后再次确认:

g++ --version

二、编写 C++ 程序

例如创建 hello.cpp

#include <iostream>
using namespace std;

int main() {
    cout << "Hello CentOS" << endl;
    return 0;
}

三、编译 C++ 程序

1️⃣ 基本编译

g++ hello.cpp -o hello
  • hello.cpp:源文件
  • -o hello:生成可执行文件 hello

2️⃣ 运行程序

./hello

四、常用编译选项

选项 说明
-std=c++11 使用 C++11 标准
-std=c++17 使用 C++17 标准
-O2 优化编译
-Wall 显示所有警告
-g 生成调试信息(配合 gdb)

示例:

g++ -std=c++17 -O2 -Wall hello.cpp -o hello

五、多文件编译

例如:

main.cpp
func.cpp
func.h
g++ main.cpp func.cpp -o app

六、使用 Makefile(进阶)

Makefile 示例:

app: main.cpp func.cpp
	g++ -std=c++17 main.cpp func.cpp -o app

clean:
	rm -f app

使用:

make
./app
make clean

七、使用 CMake(推荐大型项目)

sudo yum install cmake

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(demo)
add_executable(app main.cpp func.cpp)

编译:

mkdir build
cd build
cmake ..
make

如果你是:

  • ✅ 刚学 C++
  • ✅ 写服务器程序
  • ✅ 需要特定版本 GCC

可以告诉我,我可以给你更具体的方案。

0