如何在 64 位系统上编译 32 位可执行文件

如何在 64 位系统上编译 32 位可执行文件

注意:我浏览了一些建议的“类似问题”,但没有发现任何看似有结论性的东西。另外,它们中的大多数似乎都是 6 年前的(从 2014 年开始),所以我希望找到一些更最新的东西(并且更有可能“有效”)。

我有一个 64 位 Ubuntu 系统,运行良好。我希望能够构建一个 32 位版本的“hello, world”。这主要是学术追求,但让它运行起来会很方便。如果用“-m32”编译“可以正常工作”就好了,但事实并非如此。更糟糕的是,我记得这曾经“可以正常工作”(在旧版本的 64 位 Linux 中),但现在不再起作用了。

观察:

$ cat hello.c
#include <stdio.h>

int main() { puts("hello, world"); return 0; }
$ gcc -m32 hello.c
In file included from hello.c:1:0:
/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory
 #include <bits/libc-header-start.h>
          ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
$

经过一番探索,我发现安装这些软件包(见下文)可能会有帮助,所以我这样做了:

apt-get install libc6-dev-i386-x32-cross

安装以下内容:

The following NEW packages will be installed:


libc6-dev-i386-x32-cross libc6-dev-x32-cross libc6-i386-x32-cross
  libc6-x32-cross linux-libc-dev-x32-cross

之后,经过一点点调整,我能够编译它,但不能链接。链接阶段给出以下错误消息:

/usr/bin/ld: cannot find Scrt1.o: No such file or directory
/usr/bin/ld: cannot find crti.o: No such file or directory
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/7/libgcc.a when searching for -lgcc
/usr/bin/ld: cannot find -lgcc
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/7/libgcc.a when searching for -lgcc
/usr/bin/ld: cannot find -lgcc
collect2: error: ld returned 1 exit status

我无法再走得更远了。

因此,任何建议都将受到感激。

答案1

您必须安装正确的开发包

sudo apt-get install build-essential libc6-dev-i386

然后它就可以工作了:

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

答案2

是的 - 事实证明您所要做的就是安装 libc6-dev-i386 - 然后一切就正常了。

谢谢你的提示!

注意:互联网上有很多令人困惑和错误的信息......

相关内容