下面按从零开始的思路,给新手一份在 Ubuntu 上配置 C++ 开发环境的实用指南,尽量简单、可操作。
Ubuntu 默认可能没有 C++ 编译器,先安装:
sudo apt update
sudo apt install build-essential
build-essential 包含:
g++(C++ 编译器)gccmake验证是否安装成功:
g++ --version
能看到版本号就 OK。
mkdir cpp_hello
cd cpp_hello
nano hello.cpp
#include <iostream>
int main() {
std::cout << "Hello Ubuntu C++" << std::endl;
return 0;
}
g++ hello.cpp -o hello
./hello
看到输出说明环境正常。
当文件变多时,用 Makefile 更方便。
示例 Makefile:
hello: hello.cpp
g++ hello.cpp -o hello
clean:
rm -f hello
使用:
make
./hello
make clean
注意:Makefile 里 命令前是 Tab,不是空格
sudo snap install code --classic
推荐插件:
sudo apt install vim
安装:
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
sudo apt install gdb
使用:
g++ -g hello.cpp -o hello
gdb ./hello
❌ 用的是 gcc 而不是 g++
✅ C++ 一定要用 g++
❌ 忘了加 -o 导致生成 a.out
✅ 建议明确命名
❌ Makefile 用空格缩进
✅ 必须用 Tab
如果你愿意,可以告诉我:
我可以给你更针对性的配置方案。