温馨提示×

Ubuntu下C++怎么搭建

小樊
46
2026-09-29 12:21:43
栏目: 编程语言

在 Ubuntu 下搭建 C++ 开发环境,一般只需要安装编译器、构建工具和可选的 IDE。下面从最基础到常用组合一步步说。


一、安装基础 C++ 编译环境(必须)

1. 更新软件源

sudo apt update

2. 安装 GCC / G++(C++ 编译器)

sudo apt install g++ build-essential
  • g++:C++ 编译器
  • build-essential:包含 gcc、g++、make 等基础工具

3. 验证是否安装成功

g++ --version

看到版本号就说明 OK。


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

1. 创建文件

mkdir ~/cpp-test
cd ~/cpp-test
nano hello.cpp

2. 写入代码

#include <iostream>

int main() {
    std::cout << "Hello Ubuntu C++" << std::endl;
    return 0;
}

3. 编译并运行

g++ hello.cpp -o hello
./hello

输出:

Hello Ubuntu C++


三、使用 Make 管理(进阶一点)

示例 Makefile

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

clean:
	rm -f hello

使用:

make
./hello
make clean

四、使用 CMake(推荐,工程化)

1. 安装 CMake

sudo apt install cmake

2. 项目结构

cpp-test/
├── CMakeLists.txt
└── hello.cpp

3. CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(Hello)

add_executable(hello hello.cpp)

4. 编译

mkdir build
cd build
cmake ..
make
./hello

五、安装 IDE / 编辑器(可选)

1. VS Code(最推荐)

sudo apt install code

或官网下载 .deb

插件必装:

  • C/C++
  • CMake Tools
  • Code Runner

2. CLion(商业,学生免费)

sudo snap install clion --classic

3. 终端编辑器

  • vim
  • nano

六、调试工具(强烈推荐)

sudo apt install gdb

使用:

g++ -g hello.cpp -o hello
gdb ./hello

七、最小可用环境总结

✅ 新手最低配置:

Ubuntu + g++ + 终端

✅ 工程推荐:

Ubuntu + g++ + CMake + VS Code + GDB

如果你愿意,我可以:

  • 帮你配 VS Code 完整 C++ 环境
  • 给你一个 CMake 多文件项目模板
  • 讲 Ubuntu 下 C++ 多线程 / 网络编程环境

你现在是学习 C++还是做项目?

0 踩