How to Compile 32-bit Apps on 64-bit Ubuntu?

2019-01-17 06:28发布

I'm trying to compile a 32-bit C application on Ubuntu Server 12.04 LTS 64-bit using gcc 4.8. I'm getting linker error messages about incompatible libraries and skipping -lgcc. What do I need to do to get 32 bit apps compiled and linked?

3条回答
The star\"
2楼-- · 2019-01-17 06:37

Ubuntu 16.04

sudo apt-get install gcc-multilib

For some reason, on Ubuntu 17.04, I also needed to install the version specific one:

sudo apt-get install gcc-6-multilib

Then a minimal hello world:

#include <stdio.h>

int main() {
    puts("Hello world!");
    return 0;
}

compiles without warning under:

gcc -m32 -pedantic-errors -std=c89 -Wall hello_world.c

and:

./a.out

gives: Hello world! as expected, and:

file a.out

says:

a.out: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=87c87a83878ce7e7d23b6236e4286bf1daf59033, not stripped

and:

qemu-i386 a.out

also gives: Hello world! but would fail for an x86_64 executable

Furthermore, I have:

So I think it works :-)

See also: Cannot find crtn.o, linking 32 bit code on 64 bit system

It is a shame that this package conflicts with the cross compilers like gcc-arm-linux-gnueabihf https://bugs.launchpad.net/ubuntu/+source/gcc-defaults/+bug/1300211

Running versions of the question:

We are able to run 32-bit programs directly on 64-bit Ubuntu because the Ubuntu kernel is configured with:

CONFIG_IA32_EMULATION=y

according to:

grep CONFIG_IA32_EMULATION "/boot/config-$(uname -r)"

whose help on the kernel source tree reads:

Include code to run legacy 32-bit programs under a
64-bit kernel. You should likely turn this on, unless you're
100% sure that you don't have any 32-bit programs left.

This is in turn possible because x86 64 bit CPUs have a mode to run 32-bit programs that the Linux kernel uses.

TODO: what options does gcc-multilib get compiled differently than gcc?

查看更多
Ridiculous、
3楼-- · 2019-01-17 06:43

Multiarch installation is supported by adding the architecture information to the package names you want to install (instead of installing these packages using alternative names, which might or might not be available).

See this answer for more information on (modern) multiarch installations.

In your case you'd be better off installing the 32bit gcc and libc:

sudo apt-get install libc6-dev:i386 gcc:i386

It will install the 32-bit libc development and gcc packages, and all depending packages (all 32bit versions), next to your 64-bit installation without breaking it.

查看更多
聊天终结者
4楼-- · 2019-01-17 06:52

To get Ubuntu Server 12.04 LTS 64-bit to compile gcc 4.8 32-bit programs, you'll need to do two things.

  1. Make sure all the 32-bit gcc 4.8 development tools are completely installed:

    sudo apt-get install lib32gcc-4.8-dev

  2. Compile programs using the -m32 flag

    gcc pgm.c -m32 -o pgm

查看更多
登录 后发表回答