Compiling a C program for different hardware architectures, such as x86 desktop and embedded systems, requires understanding the specific requirements and tools for each environment. This guide will walk you through the process of compiling C code for both x86 desktop systems and embedded hardware, highlighting key considerations and tools for successful compilation.
If we consider that we are working on two platforms,
1. x86 – 32 or 64 bit i.e. laptop / desktop
2. ARM – Lets say Raspberry Pi
In this case, we will need to compile some programs which needs to run on x86 / desktop and some programs which needs to run on ARM platform. So, the programs which are compiled on x86 and runs on x86 i.e. compilation and execution on same platform, are called as “native compilation”
Now, when we need to run some programs on ARM, in normal scenario we download toolchain for ARM, and compile the program on x86, so in this case we compile a program on one platform i.e. x86 but run on another platform i.e. ARM, this is called as “cross compilation”
Now, lets see how native compilation happens,
1. Create a hello world program with vim on Ubuntu desktop / laptop as,
$ vim helloworld.c
#include <stdio.h>
int main(int argc, char **argv) {
printf("hello world\n");
return 0;
}
Now, compile the program on ubuntu and to run here ( on ubuntu ) itself as,
$ gcc -o helloworld helloworld.c
Now, if you see the output binary generated, you will see like this,
$ file helloworld
helloworld: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=b397310c8ddfabbdbe75f8021bea768321218984, for GNU/Linux 3.2.0, not stripped
So, it shown that generated binary is executable for intel 80386 / x86 since my laptop is 32 bit. Now, we will be able execute the same program on same terminal since we compile on x86 to execute on x86 as,
$ ./helloworld
hello world
Now, lets try to understand cross compilation i.e. compile on x86 which will generate binary for ARM and to run on ARM.
for this, we need set of tools which are called as cross compiler or standard word is “toolchain” which helps to compile for ARM on x86 as,
$ git clone https://github.com/raspberrypi/tools --depth 1
$ cd tools
$ git branch
* master
Export Toolchain path
$ export PATH=$PATH:/home/myuser/rpi/tools/arm-bcm2708/arm-bcm2708-linux-gnueabi/bin
We need to use gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc for compilation of program. For this you can export path like,
$ export PATH=$PATH:/home/myuser/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin
and compile the program as,
$ arm-linux-gnueabihf-gcc -o helloworld helloworld.c
$ file helloworld
ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-armhf.so.3, for GNU/Linux 2.6.26, BuildID[sha1]=4a95b9df54776ae6240b17d0f3d4d9aa4ab00715, not stripped
And now try this compiled program on RPi.