温馨提示×

怎样在ubuntu测c加加代码

小樊
34
2026-10-19 23:45:56
栏目: 智能运维

在 Ubuntu 上测试(编译、运行、调试)C++ 代码,一般按下面几步来:


一、安装 C++ 编译环境

Ubuntu 默认可能没有 g++,先安装:

sudo apt update
sudo apt install g++ build-essential

检查是否安装成功:

g++ --version

二、写一个 C++ 示例程序

创建文件 test.cpp:

#include <iostream>
using namespace std;

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

三、编译 C++ 代码

1️⃣ 基本编译

g++ test.cpp -o test

2️⃣ 开启调试信息(推荐)

g++ -g test.cpp -o test

3️⃣ 开启警告(好习惯)

g++ -Wall -Wextra -g test.cpp -o test

四、运行程序

./test

输出:

Hello Ubuntu C++


五、调试(可选但很重要)

使用 gdb 调试

gdb ./test

常用 gdb 命令:

  • run 运行
  • break main 设断点
  • next 单步
  • print 变量名 查看变量
  • quit 退出

六、多文件 C++ 项目示例

g++ main.cpp func.cpp -o app

或写一个简单的 Makefile:

app: main.cpp func.cpp
	g++ -g -Wall main.cpp func.cpp -o app

使用:

make
./app

七、快速测试(不想写文件)

g++ -x c++ - <<'EOF'
#include <iostream>
int main(){ std::cout << "test\n"; }
EOF
./a.out

八、常用工具推荐

  • gdb:调试
  • valgrind:内存检查
  • clang++:替代编译器
  • vscode / vim:编辑器

如果你有具体代码或想测试某类程序(算法 / 多线程 / 网络),可以发出来,我可以直接帮你跑和改。

0 踩