下面以 Debian 系统 为例,介绍如何使用 GCC 编译 C / C++ 程序,从安装到常见用法。
gcc --version
g++ --version
如果能看到版本号,说明已安装。
sudo apt update
sudo apt install gcc g++ make
Debian 12(Bookworm)默认仓库中 GCC 版本较新,安装即可使用。
// hello.c
#include <stdio.h>
int main() {
printf("Hello, Debian GCC!\n");
return 0;
}
gcc hello.c -o hello
./hello
// hello.cpp
#include <iostream>
int main() {
std::cout << "Hello C++!" << std::endl;
return 0;
}
g++ hello.cpp -o hello
./hello
gcc -Wall -Wextra -O2 hello.c -o hello
gcc -g hello.c -o hello
gcc -std=c11 hello.c -o hello
g++ -std=c++17 hello.cpp -o hello
main.c
foo.c
foo.h
gcc main.c foo.c -o app
或分步编译:
gcc -c foo.c # 生成 foo.o
gcc -c main.c # 生成 main.o
gcc foo.o main.o -o app
CC = gcc
CFLAGS = -Wall -O2
app: main.o foo.o
$(CC) main.o foo.o -o app
clean:
rm -f *.o app
编译:
make
清理:
make clean
sudo apt install build-essential
gcc math.c -o math -lm
sudo apt install gcc g++ make
gcc hello.c -o hello
./hello
如果你有 具体语言(C / C++ / 混合)、项目结构 或 报错信息,可以贴出来,我可以帮你具体分析。