Cross-Compile Simple C++ Program for Raspberry Pi on Ubuntu

Cross-compilation is a process when source code is compiled into executable code on one platform and will run on another platform. For example, a program was compiled on 64-bit PC (amd64) but it will run on ARM hard-float (armhf) based single-board computer.

This tutorial shows how to cross-compile simple C++ program for Raspberry Pi on Ubuntu.

On Ubuntu, run the following command to install GNU C++ cross-compiler that is used to compile source code for armhf architecture:

sudo apt install -y g++-arm-linux-gnueabihf

After the install process is finished check cross-compiler version:

arm-linux-gnueabihf-g++ --version

Create a main.cpp file and add the following code:

#include <iostream>

int main() {
    std::cout << "Hello world" << std::endl;

    return 0;
}

Compile this code by using the following command:

arm-linux-gnueabihf-g++ main.cpp -o main

Transfer program to Raspberry Pi using scp tool:

scp main pi@192.168.0.184:~/

Connect to Raspberry Pi via SSH:

ssh pi@192.168.0.184

Run the program:

./main

Leave a Comment

Your email address will not be published. Required fields are marked *