Sunday, January 22, 2012

Hello World

In the last post, I talked about how to get a development environment up and running on your PC. You'll need to do that if you haven't done so already:

2012-01-22 Since the initial writing, there has been a new virtual machine released, which streamlines some of this. This post has been updated to reflect these changes.
Let's get some actual code compiled!

Login like you did in the first tutorial, and you should see the Linux desktop:

Double click the Raspberry Pi Development icon to start a terminal session.

My version of the virtual machine came with a "Hello World" example already in place. That's great for checking validity of the system, but not so hot for learning how to do things from the ground up... So let's create hello2.

Make a directory for our Hello, World program
mkdir hello2

Go into it
cd hello2

Now we need to enter a text editor. Linux has a variety of text editors you can use (with lots of heated debate as to which is best). For now I'm going to use Pico because it's quick/easy for folks more familiar with Windows.

pico hello2.cpp

Now, you can copy/paste the following source into pico by copying here, and then right-clicking in the terminal window and selecting Paste

/* Hello World program */
#include <stdio.h>
    printf("Hello, world!\n");

Press Ctrl-X to exit Pico

It will ask you if you want to save the buffer. Press Y
Confirm the file name: hello2.cpp

Now we're back to the command prompt. We're going to compile the code you've just written using a tool called Scratchbox2. Scratchbox2's main job is to provide a cross-compiling environment, in this case for ARM. It also provides an emulator so that you can run the binaries we'll be creating... Seriously handy stuff.

You can go into ScratchBox2 in either single-command or interactive mode. I prefer single-command mode so I don't have to drop in/out of interactive mode as I edit files in pico (if you're using vi or another editor, you may not have this problem).

So, to run a command under ScratchBox2, you type:
sb2 [command]

So, for us to compile our source file to an executable file, called "hello" (note the lack of extension, this is on purpose for Linux), we issue the following command:
sb2 gcc hello2.cpp -o hello2

If you want to learn about a file (such as check to see what environment it's compiled for), you use the file command. In this case, we don't need to emulate that in ScratchBox, so we enter:
file hello2

The response should be a bit like this (target cpu emphasis mine)
hello: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.16, not stripped

To run our program in ScratchBox's emulator, enter the following:
sb2 ./hello2

Congrats, you now have Hello, World running in an emulated ARM environment! You can exit the terminal by entering:


  1. Thanks for your usefull blob.

    Pay attention, the run command is :
    sb2 ./hello2

    Bye Roberto