2025-10-23    2026-01-01    450 字  1 分钟

The note is generated by ChatGPT.

1. Install C++ Environment

在 Linux 或 WSL 里,C/C++ 程序需要编译器。常用的是 g++(GNU C++ compiler)。
同时,调试程序需要 gdb(GNU Debugger)。

运行:

1
2
sudo apt update
sudo apt install -y build-essential gdb

检查是否安装成功:

1
2
g++ --version
gdb --version

2. Normal Way to Compile and Run C++

这是最常见、最基本的用法:

  1. 写代码 hello.cpp

    1
    2
    3
    4
    5
    6
    7
    
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello from Linux C++!" << endl;
        return 0;
    }
    
  2. 编译

    1
    
    g++ hello.cpp -o hello
    

    👉 把 hello.cpp 编译成可执行文件 hello

  3. 运行

    1
    
    ./hello
    

    👉 输出:

    Hello from Linux C++!
    

⚠️ 注意:和 Python 的 python hello.py 不同,C++ 必须先编译再运行。


3. Create cprun Helper Function

C++ 每次都要先编译再运行,比较麻烦。
为了方便,我们写一个 shell 函数 cpprun,让你一条命令就能完成编译+运行。

~/.zshrc~/.bashrc 里加上以下内容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
cpprun() {
  # 1. Check arguments
  if [ -z "$1" ]; then
    echo "Usage: cprun <source-file> [args...]"
    return 1
  fi

  # 2. Check file existence
  if [ ! -f "$1" ]; then
    echo "Error: file '$1' not found"
    return 1
  fi

  # 3. Generate output file name
  src="$1"
  base=$(basename "$src")
  name="${base%.*}"
  outfile="/tmp/${name}.out"

  # 4. Debug mode
  if [ "$2" = "--debug" ]; then
    echo "Compiling in debug mode..."
    g++ -std=c++17 -g -Wall "$src" -o "$outfile" && gdb "$outfile"
    return
  fi

  # 5. Normal compile & run
  echo "Compiling $src..."
  g++ -std=c++17 -O2 -Wall "$src" -o "$outfile" && "$outfile" "${@:2}"
}

让配置生效:

1
source ~/.zshrc

4. Run with cpprun

  1. 直接运行

    1
    
    cpprun hello.cpp
    
  2. 传递参数

    1
    
    cpprun hello.cpp arg1 arg2
    
  3. 调试模式

    1
    
    cpprun hello.cpp --debug