温馨提示×

Ubuntu 下怎么编译 C++ 码

小樊
38
2026-10-11 06:39:59
栏目: 编程语言

在 Ubuntu 下编译 C++ 代码通常很简单,常用的是 g++(GNU C++ 编译器)。下面从最基础到常见用法一步步说明。


一、安装编译工具

一般 Ubuntu 默认可能没有 g++,先安装:

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

build-essential 包含了 gcc、g++、make 等基础工具。

验证是否安装成功:

g++ --version

二、写一个简单的 C++ 程序

创建文件 hello.cpp:

#include <iostream>
using namespace std;

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

三、最基础的编译方式

g++ hello.cpp

默认会生成可执行文件 a.out:

./a.out

四、指定输出文件名

g++ hello.cpp -o hello

运行:

./hello

五、常用编译选项

1. 开启警告(推荐)

g++ -Wall hello.cpp -o hello

2. 开启调试信息(用 gdb 调试)

g++ -g hello.cpp -o hello

3. 开启优化

g++ -O2 hello.cpp -o hello

4. C++ 标准版本

g++ -std=c++11 hello.cpp -o hello
g++ -std=c++17 hello.cpp -o hello

六、多文件编译

例如:

main.cpp
math_utils.cpp
math_utils.h

编译:

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

七、使用 Makefile(进阶)

示例 Makefile:

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

clean:
	rm -f app

使用:

make
./app
make clean

八、使用 CMake(工程化推荐)

CMakeLists.txt 示例:

cmake_minimum_required(VERSION 3.10)
project(demo)

set(CMAKE_CXX_STANDARD 17)

add_executable(app main.cpp math_utils.cpp)

编译:

mkdir build
cd build
cmake ..
make
./app

如果你有 具体代码 / 多文件项目 / 第三方库(如 OpenCV、Boost),可以贴出来,我可以给你更针对性的编译命令。

0 踩