在 Ubuntu 下用 C++ 编译和运行程序,一般步骤如下:
Ubuntu 默认可能没装 g++,先安装:
sudo apt update
sudo apt install g++ -y
验证:
g++ --version
例如,创建文件 hello.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Hello Ubuntu!" << endl;
return 0;
}
创建文件:
nano hello.cpp
(或用 vim、gedit 等)
g++ hello.cpp -o hello
hello.cpp:源文件-o hello:生成可执行文件 hellog++ -std=c++17 -Wall -O2 hello.cpp -o hello
说明:
-std=c++17:使用 C++17 标准-Wall:显示警告-O2:优化编译./hello
输出:
Hello Ubuntu!
例如:
main.cppfunc.cppg++ main.cpp func.cpp -o app
./app
sudo apt install cmake -y
CMakeLists.txtcmake_minimum_required(VERSION 3.10)
project(demo)
add_executable(demo main.cpp)
mkdir build
cd build
cmake ..
make
./demo
❌ command not found: g++
✅ 没装编译器,看第一步
❌ permission denied
✅ 用 ./程序名,不是 程序名
如果你愿意,我可以:
你想用哪种方式?