gccraspberry-pidebian-bookworm

C Code compiled on Raspbian Bookworm won't run on Buster


When I compile code on a Raspberry Pi running the latest Bookworm release, it won't run on a Raspberry Pi with Buster. It returns cannot execute binary file: Exec format error. Why?

Compile on Bookworm:

pi@Bookworm:~ $ gcc -o hello_world hello_world.c
pi@Bookworm:~ $ ./hello_world 
Hello world!
pi@Bookworm:~ $ scp hello_world pi@Buster.local:/home/pi/

pi@Bookworm~ $ cat /etc/issue
Debian GNU/Linux 12 \n \l
pi@WBookworm:~ $ gcc --version
gcc (Debian 12.2.0-14) 12.2.0

Then run it on Buster:

pi@Buster:~ $ ./hello_world 
-bash: ./hello_world: cannot execute binary file: Exec format error

pi@Buster:~ $ cat /etc/issue
Raspbian GNU/Linux 10 \n \l
pi@Buster:~ $ gcc --version
gcc (Raspbian 8.3.0-6+rpi1) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

And just in case the file was corrupted in scp transit, I copied the same file back to Bookworm over scp as hello_world_back and it ran just fine.

$ ./hello_world_back
Hello world!

Solution

  • The problem is that the Buster install is 32-bit Raspbian (the default for Buster), and the Bookworm install is 64-bit Raspbian (the new preferred image). When you compile on a 64-bit machine, it makes a 64-bit compiled binary. And you cannot run a 64-bit program on a 32-bit Raspbian OS, even if the underlying hardware has a 64-bit capable processor (which all 3B+ and higher including my Buster install do).

    Bottom line: binary images created with gcc cannot be run on 32-bit Linux if compiled on 64-bit Linux unless you go to the extra effort to create a 32-bin binary.