在 Ubuntu 下编译 C++ 程序,常用方法是使用 g++(GNU 编译器)。下面从基础到进阶给你一个完整说明。
大多数 Ubuntu 已经自带,如果没有,执行:
sudo apt update
sudo apt install g++
查看版本(确认安装成功):
g++ --version
创建文件 hello.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, Ubuntu!" << endl;
return 0;
}
g++ hello.cpp -o hello
hello.cpp:源文件-o hello:指定输出文件名(如果不写,默认是 a.out)运行:
./hello
g++ -Wall hello.cpp -o hello
g++ -std=c++17 hello.cpp -o hello
g++ -g hello.cpp -o hello
g++ -O2 hello.cpp -o hello
main.cpp
math_utils.cpp
math_utils.h
g++ main.cpp math_utils.cpp -o app
g++ -c math_utils.cpp # 生成 math_utils.o
g++ -c main.cpp # 生成 main.o
g++ main.o math_utils.o -o app
Makefile 示例:
CXX = g++
CXXFLAGS = -Wall -std=c++17
app: main.o math_utils.o
$(CXX) main.o math_utils.o -o app
main.o: main.cpp
$(CXX) $(CXXFLAGS) -c main.cpp
math_utils.o: math_utils.cpp
$(CXX) $(CXXFLAGS) -c math_utils.cpp
clean:
rm -f *.o app
使用:
make
./app
make clean
CMakeLists.txtcmake_minimum_required(VERSION 3.10)
project(MyApp)
set(CMAKE_CXX_STANDARD 17)
add_executable(app main.cpp math_utils.cpp)
mkdir build
cd build
cmake ..
make
./app
确保你用的是 g++,而不是 gcc:
g++ test.cpp
chmod +x hello
sudo apt install g++
g++ -std=c++17 -Wall hello.cpp -o hello
./hello
如果你愿意,我可以:
你现在是 学习 C++,还是 在写具体项目?