在 Ubuntu 下编译 C++ 程序,通常有命令行和IDE两种方式,下面是最常用、最基础的说明。
一般 Ubuntu 自带 g++,如果没有,先安装:
sudo apt update
sudo apt install g++ build-essential
验证:
g++ --version
例如 hello.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Hello Ubuntu!" << endl;
return 0;
}
基本编译:
g++ hello.cpp
会生成可执行文件 a.out
运行:
./a.out
g++ hello.cpp -o hello
./hello
g++ -std=c++17 hello.cpp -o hello # 指定 C++ 标准
g++ -Wall hello.cpp -o hello # 显示警告
g++ -O2 hello.cpp -o hello # 优化
例如:
main.cpp
func.cpp
func.h
g++ main.cpp func.cpp -o program
Makefile 示例:
program: main.cpp func.cpp
g++ main.cpp func.cpp -o program
clean:
rm -f program
使用:
make
./program
make clean
g++ 编译chmod +x hello
确认路径或使用 -I 指定:
g++ main.cpp -I./include
如果你愿意,可以告诉我:
我可以直接给你对应示例。