在 Debian 上用 GCC 静态编译(static linking),核心思路是:
让链接阶段使用 .a 静态库,而不是 .so 动态库。
下面按常见场景详细说明。
gcc -static hello.c -o hello
✅ 效果:
libc.so检查:
file hello
ldd hello
期望看到:
statically linked
not a dynamic executable
Debian 默认不安装静态 glibc,会报错:
/usr/bin/ld: cannot find -lc
✅ 解决方法:
sudo apt update
sudo apt install libc6-dev
sudo apt install glibc-static
如果 glibc-static 不存在(某些版本),安装:
sudo apt install libc6-dev
并检查是否有:
ls /usr/lib/x86_64-linux-gnu/libc.a
原因:
getaddrinfo)✅ 推荐方案(见第四节)
g++ main.cpp -static-libstdc++ -o main
gcc main.c -static-libgcc -o main
g++ main.cpp -static-libgcc -static-libstdc++ -o main
sudo apt install musl-tools
musl-gcc hello.c -o hello
✅ 特点:
检查:
file hello
ldd hello
sudo apt install musl-tools
musl-gcc -static hello.cpp -lstdc++ -o hello
或使用 g++:
g++ -static hello.cpp -o hello
(前提:有静态 libstdc++)
cannot find -lc✅ 安装静态 glibc 或改用 musl
undefined reference✅ 检查是否漏链接库:
-lm -lpthread -ldl
✅ 用 musl 编译
| 场景 | 推荐方式 |
|---|---|
| 学习 / 简单程序 | gcc -static |
| 生产 / 部署 | musl 静态编译 |
| 只静态 C++ 库 | -static-libstdc++ |
| Debian 官方包 | 不推荐完全静态 glibc |
如果你愿意,可以告诉我:
我可以给你一个 完全可用的编译方案。