温馨提示×

Ubuntu下C++怎么编译

小樊
45
2026-09-05 11:32:06
栏目: 编程语言

在 Ubuntu 下编译 C++ 程序,通常有以下几种常见方式。下面从最基础常用工具一步步说明。


一、使用 g++ 编译(最常用)

1️⃣ 安装编译器

一般 Ubuntu 自带 g++,如果没有:

sudo apt update
sudo apt install g++ build-essential

2️⃣ 写一个简单的 C++ 程序

比如 hello.cpp

#include <iostream>
using namespace std;

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

3️⃣ 编译

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

4️⃣ 运行

./hello

输出:

Hello Ubuntu!

二、常用编译选项

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

说明:

  • -std=c++17:使用 C++17 标准(可选 11 / 14 / 20)
  • -Wall:显示所有警告
  • -O2:开启优化

三、多个源文件编译

假设有:

main.cpp
func.cpp
func.h

编译方式:

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

或者分步编译:

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

四、使用 CMake(推荐项目使用)

1️⃣ 安装 CMake

sudo apt install cmake

2️⃣ 示例目录

project/
├── CMakeLists.txt
└── main.cpp

3️⃣ CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(demo)

set(CMAKE_CXX_STANDARD 17)

add_executable(demo main.cpp)

4️⃣ 编译

mkdir build
cd build
cmake ..
make

运行:

./demo

五、使用 Makefile(轻量项目)

示例 Makefile

hello: hello.cpp
	g++ hello.cpp -o hello

clean:
	rm -f hello

使用:

make
./hello
make clean

六、常见错误排查

  • g++: command not found → 没装编译器
  • Permission denied → 忘了 ./
  • ❌ 找不到头文件 → 检查 -I 路径

如果你愿意,可以告诉我:

  • 单文件练习还是项目开发
  • 用的 C++ 标准版本
  • 是否需要 第三方库(如 OpenCV / Boost)

我可以直接给你最合适的编译方式。

0