Our First Program in C (PI5)

Aus C und Assembler mit Raspberry

Our first program will initially do nothing. It will simply run an infinite loop. This serves as a basic building block for all further experiments. I will explain how to create, compile, and run such a program. First, let's check if everything works.

Creating the Source Code

Unfortunately, when working with BareMetal, we can't avoid using Assembly language, even though the Assembly program doesn't do much at the moment. It will be needed later, for example, for interrupt programming.

Open a text editor to write our first Assembly program:

//
// The first program
// 01.07.2024 www.satyria.de
//
.section .init    // Ensure the linker places this at the beginning of the kernel image
.globl _start     // Generates a global label
_start:           // The label _start (entry address)

   mov sp, #0x80000 // Create a stack of 512KB (524288 bytes)
   b main           // Branch to "main"

Save the file in the default directory under Windows: C:\msys64\home\xxx (where xxx is usually your username). On Linux, you can save the file in the home directory. Name the file first.S. The .S extension indicates that the file is Assembly source code.

Since we want to program in C, let's write a small main function:

//
// main.c
//

int main(void)
{
    while (1) {}
}

This simply creates an infinite loop.

Compiling the Program with make

Previously, I described how to write a Makefile under "Working with Make and Linker Script." With this Makefile, we can also compile this program if the files "Makefile" and "linker.ld" are present in the directory:

make

You can download the source code as a ZIP file from the following link: https://www.satyria.de/arm/sources/C/first.zip