Monday, September 14, 2015

Cross compiling for Raspberry Pi

So since my main project (http://www.github.com/thepoho/gameshow) for the Gameshow Pinball Machine now includes a web server (mongoose) and a json library (rapid json) and threads and wiring pi, i was getting fed up with the super long compile times on the pi itself.  It was taking about 30 seconds to compile and run.  Being used to interpreted high level languages, i deemed this unacceptable and went about trying to find a faster way of getting my iterative development process running.  My main plan was this:

  • Do my development locally on my laptop (well inside a vm running ubuntu)
  • Press the go button which would
    • Cross compile in ubuntu for arm
    • scp the binary to my raspberry pi
    • start an interactive ssh shell on the pi running my freshly copied binary

There are a bunch of tutorials out there about cross compiling for the rpi.  I got these working, but since I was using the WiringPi library (http://wiringpi.com/) I was having some trouble compiling it in.  You generally need the .so file which has been compiled for the target architecture - in this case, arm.  I grabbed libwiringpi.so and chucked it in my project.  You also need the .h files for the project, but as these are just plain text, they'll work cross platform.  My source files are in /src and /include.  The wiring pi files are in wiring_pi.
After grabbing the cross compiler from the official raspberry pi git repo (https://github.com/raspberrypi/tools/) and following the guide here http://hertaville.com/2012/09/28/development-environment-raspberry-pi-cross-compiler/ , my compile line ended up looking like this:

arm-linux-gnueabihf-g++ -Wall -std=c++0x -pthread -D _DEBUG -D _LINUX -D GAMESHOW_BUILD_RASPI -I/home/poho/git/gameshow/wiring_pi/include -L/home/poho/git/gameshow/wiring_pi/lib_arm  -Wl,--start-group /home/poho/git/gameshow/wiring_pi/lib_arm/libWiringPi.so -Wl,--end-group -iquote ./include ./src/*.cpp ./src/*.c -o gameshow_arm

lib_arm contains libWiringPi.so (copied from my pi) and wiring_pi/include has all the wiring pi .h files.  Both the .so and .h files can be found on any system that has installed the wiring pi build tools.

From here it was a simple matter of scping the compiled file (gameshow_arm) to my pi and running the file using ssh -t.  I'd set up an rsa key pair so i wouldn't even need a password!