温馨提示×

怎样在ubuntu配置c++环境

小樊
46
2026-09-20 16:52:21
栏目: 编程语言

在 Ubuntu 上配置 C++ 开发环境通常包含以下几个步骤:安装编译器、配置构建工具、选择编辑器/IDE、以及(可选)安装调试工具。下面按从简单到完整的方式说明。


一、安装基础 C++ 编译环境

1. 更新软件源

sudo apt update

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

sudo apt install build-essential

build-essential 包含:

  • gcc(C 编译器)
  • g++(C++ 编译器)
  • make(构建工具)

3. 验证安装

g++ --version

若能看到版本号,说明安装成功。


二、编写并编译第一个 C++ 程序

1. 创建源文件

mkdir ~/cpp_demo && cd ~/cpp_demo
nano hello.cpp

写入内容:

#include <iostream>
using namespace std;

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

2. 编译

g++ hello.cpp -o hello

3. 运行

./hello

三、使用 Make 构建(推荐)

创建 Makefile

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

clean:
	rm -f hello

使用:

make
./hello
make clean

四、安装调试工具(GDB)

sudo apt install gdb

编译时加 -g

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

五、安装 CMake(中大型项目推荐)

sudo apt install cmake

示例 CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(hello)

add_executable(hello hello.cpp)

使用:

mkdir build && cd build
cmake ..
make
./hello

六、选择编辑器和 IDE

轻量级

  • VS Code(推荐)
sudo snap install code --classic

安装插件:

  • C/C++
  • CMake Tools

专业 IDE

  • CLion(收费,学生免费)
  • Qt Creator
sudo apt install qtcreator

七、安装多个 GCC 版本(可选)

sudo apt install gcc-11 g++-11
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 100

八、常见补充库(按需)

sudo apt install libboost-all-dev
sudo apt install libopencv-dev

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

  • 学习 C++ 还是做项目
  • 是否使用 CMake / 第三方库
  • 偏好 命令行还是 IDE

我可以给你一套更针对性的配置方案。

0