How to compile 32-bit program on 64- bit gcc in C and C++

C++Server Side ProgrammingProgramming

Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use this feature.

At first, we have to check the current target version of the gcc compiler. To check this, we have to type this command.

gcc –v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
...........
...........
...........

Here it is showing that Target is x86_64. So we are using the 64-bit version of gcc. Now to use the 32-bit system, we have to write the following command.

gcc –m32 program_name.c

Sometimes this command may generate some error like below. This indicates that the standard library of gcc is missing. In that situation we have to install them.

In file included from test_c.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.

Now, to install the standard library for gcc, we have to write the following commands.

sudo apt-get install gcc-multilib
sudo apt-get install g++-multilib

Now by using this code we will see the differences of executing in 32-bit system and the 64-bit system.

Example

#include<stdio.h>
main(){
   printf("The Size is: %lu\n", sizeof(long));
}

Output

$ gcc test_c.c
test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){
^~~~
$ ./a.out
The Size is: 8

Output

$ gcc -m32 test_c.c
test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){
^~~~
test_c.c: In function ‘main’:
test_c.c:4:28: warning: format ‘%lu’ expects argument of type ‘long unsigned
int’, but argument 2 has type ‘unsigned int’ [-Wformat=]
printf("The Size is: %lu\n", sizeof(long));
~~^
%u
$ ./a.out
The Size is: 4
raja
Published on 29-Apr-2019 13:37:22
Advertisements