在 Linux 下学习 C++ 是非常常见且高效的选择。下面我从环境搭建 → 学习路径 → 常用工具 → 实战练习几个方面,系统讲一下怎么用 Linux 学 C++。
常见发行版:
查看系统:
uname -a
最常用的编译器是 g++(GNU 编译器)
Ubuntu / Debian:
sudo apt update
sudo apt install g++ build-essential
CentOS:
sudo yum install gcc-c++
验证:
g++ --version
根据习惯选:
VS Code 安装(Ubuntu):
sudo apt install code
mkdir cpp_learn
cd cpp_learn
vim hello.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello Linux C++" << endl;
return 0;
}
g++ hello.cpp -o hello
./hello
练习:
g++ test.cpp -Wall -Wextra
-Wall 帮你发现潜在错误
Linux 下建议:
g++ main.cpp student.cpp -o app
重点学:
示例:
#include <vector>
#include <algorithm>
这是 Linux 学 C++ 的独特优势:
fstreamopen/read/writepthread / std::thread示例 Makefile:
app: main.cpp
g++ main.cpp -o app
clean:
rm app
使用:
make
./app
make clean
CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(learn)
add_executable(app main.cpp)
构建:
mkdir build
cd build
cmake ..
make
g++ main.cpp -g -o app
gdb ./app
常用:
break main
run
next
print x
sudo apt install valgrind
valgrind ./app
每天一个小项目:
Linux + C++ = 系统级编程能力
如果你愿意,我可以:
你想从哪一步开始?