Introduction
Cross-compiling a C program for the Raspberry Pi using GCC on Ubuntu is a powerful skill that allows developers to build applications for the Raspberry Pi from a more robust environment. This tutorial will guide you through the process of setting up your environment, creating a simple C program, and using a Makefile to streamline the build process.
Prerequisites
- Ubuntu operating system (18.04 or later recommended)
- Basic knowledge of C programming
- Familiarity with the command line
- Access to a Raspberry Pi (for testing the compiled program)
Parts/Tools
- GCC (GNU Compiler Collection)
- Raspberry Pi cross-compiler toolchain
- Make utility
- Text editor (e.g., Vim, Nano, Visual Studio Code)
Steps
-
Install Required Packages
- Open a terminal and update your package list:
- Install the cross-compiler toolchain:
- Install Make utility:
sudo apt update
sudo apt install gcc-arm-linux-gnueabi
sudo apt install make
-
Create Your C Program
- Create a new directory for your project:
- Create a C file, e.g.,
hello.c
: - Write a simple C program:
- Save and exit the editor.
mkdir my_raspberry_pi_project && cd my_raspberry_pi_project
nano hello.c
#include <stdio.h> int main() { printf("Hello, Raspberry Pi!n"); return 0; }
-
Create a Makefile
- Create a file named
Makefile
: - Write the following content in the Makefile:
- Save and exit the editor.
nano Makefile
CC = arm-linux-gnueabi-gcc CFLAGS = -Wall -Wextra TARGET = hello all: $(TARGET) $(TARGET): hello.o $(CC) $(CFLAGS) -o $@ $^ hello.o: hello.c $(CC) $(CFLAGS) -c $< clean: rm -f $(TARGET) *.o
- Create a file named
-
Compile Your Program
- Run the following command in the terminal:
- If successful, you should see
hello
executable in your directory.
make
-
Transfer and Test on Raspberry Pi
- Transfer the compiled program to your Raspberry Pi using SCP:
- SSH into your Raspberry Pi:
- Run the program:
- You should see the output:
Hello, Raspberry Pi!
scp hello pi@:~
ssh pi@
./hello
Troubleshooting
- Issue: Compiler not found.
- Issue: Errors during compilation.
- Issue: Program does not run on Raspberry Pi.
Solution: Ensure you have installed the cross-compiler toolchain correctly. Check with which arm-linux-gnueabi-gcc
.
Solution: Verify your C code for syntax errors and ensure you are using the correct flags in the Makefile.
Solution: Ensure you have transferred the executable correctly and that it has execute permissions. Run chmod +x hello
on the Raspberry Pi.
Conclusion
Congratulations! You have successfully cross-compiled a C program for the Raspberry Pi using GCC on Ubuntu. By leveraging a Makefile, you can streamline your build process for future projects. Explore further by adding more features to your C program and experimenting with different libraries.