在 Ubuntu 下编译 C++ 代码通常很简单,常用的是 g++(GNU C++ 编译器)。下面从最基础到常见用法一步步说明。
一般 Ubuntu 默认可能没有 g++,先安装:
sudo apt update
sudo apt install g++ build-essential
build-essential 包含了 gcc、g++、make 等基础工具。
验证是否安装成功:
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++ -Wall hello.cpp -o hello
g++ -g hello.cpp -o hello
g++ -O2 hello.cpp -o hello
g++ -std=c++11 hello.cpp -o hello
g++ -std=c++17 hello.cpp -o hello
例如:
main.cpp
math_utils.cpp
math_utils.h
编译:
g++ main.cpp math_utils.cpp -o app
示例 Makefile:
app: main.cpp math_utils.cpp
g++ -std=c++17 -Wall main.cpp math_utils.cpp -o app
clean:
rm -f app
使用:
make
./app
make clean
CMakeLists.txt 示例:
cmake_minimum_required(VERSION 3.10)
project(demo)
set(CMAKE_CXX_STANDARD 17)
add_executable(app main.cpp math_utils.cpp)
编译:
mkdir build
cd build
cmake ..
make
./app
如果你有 具体代码 / 多文件项目 / 第三方库(如 OpenCV、Boost),可以贴出来,我可以给你更针对性的编译命令。