如何在 Ubuntu-64 位环境下编译 32 位程序

如果 gcc 编译时直接用 -m32 选项,则会由于找不到一些库而报错:

1
2
3
4
5
6
$ gcc -g -m32 hello.c -o hello
In file included from hello.c:1:
/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: 没有那个文件或目录
27 | #include <bits/libc-header-start.h>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.

需要提前安装好 32 位程序所需要的依赖环境:

1
2
3
sudo apt-get update
sudo apt-get install build-essential module-assistant
sudo apt-get install gcc-multilib g++-multilib

然后再用 -m32 选项编译程序即可:

1
gcc -g -m32 hello.c -o hello
1
2
$ file hello
hello: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, BuildID[sha1]=7b812a0a70b42698b421cc3e4b2db23c26d48a14, for GNU/Linux 3.2.0, with debug_info, not stripped