Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

main.c

#include <stdio.h>

int main(void) {
    puts("hello world");
    return 0;
}

compiles without warning with:

gcc -m32 -ggdb3 -O0 -pedantic-errors -std=c89 
  -Wall -Wextra -pedantic -o main.out main.c

And

./main.out

outputs:

hello world

And:

file main.out

says:

main.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 main.out

also gives:

hello world

but fails on an x86_64 executable with:

./main.out: Invalid ELF image for this architecture

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...