3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クロスコンパイル環境の整理(for Raspberry Pi)

Posted at

#1.この記事の内容

C言語のARM向けクロスコンパイル環境をDockerfileで整理しました.
クロスコンパイル環境一式はGitHubに公開しています.

ビルドしたプログラムの動作確認には,Raspberry Pi 4B 8GBを使用しました.
OSはRaspbianで,armv7l(32bit)とaarch64(64bit)の2種について紹介します.aarch64は公式サポートされていませんが,
Raspberry Pi OS (64 bit) beta test version
にテストバージョンへのリンクが掲載されています.

ビルドを行うマシンはWindows11上に構築したWSL2(Ubuntu 20.04)です.

#2.クロスコンパイル手順

本記事ではクロスコンパイル環境をDockerイメージとして構築します.
ベースとするイメージは,ubuntu:22.04として,クロスコンパイルとビルドしたファイルを転送する為に必要なパッケージをインストールします.

armv7l向けのコンパイルにはarm-linux-gnueabihf-gccを,aarch64向けのコンパイルにはaarch64-linux-gnu-gccを使用します.

クロスコンパイルの際の注意点としては,動的リンクする場合に,クロスコンパイル環境上のライブラリのバージョンと,動作させるボード(今回の場合はRaspberry Pi)にインストールしているライブラリのバージョンを合わせる必要があります.
今回は,-staticオプションをつけることで静的にリンクし,実行体に組込まれるように実装しました.

##2-1.armv7l

$ git clone https://github.com/ryoma-jp/samples.git
$ cd samples/env/cross_compile/docker_armv7l/
$ docker build -t env_xc_armv7l/ubuntu:22.04 .
$ ./docker_run.sh
# cd /work/sample_source
# make -f Makefile_for_xc_armv7l
# file sample_armv7l
sample_armv7l: ELF 32-bit LSB executable, ARM, EABI5 version 1 (GNU/Linux), statically linked, 
BuildID[sha1]=5499e43859ab2244f2ec8179590b929c4767dd71, for GNU/Linux 3.2.0, not stripped

#2-2.aarch64

$ git clone https://github.com/ryoma-jp/samples.git
$ cd samples/env/cross_compile/docker_aarch64/
$ docker build -t env_xc_aarch64/ubuntu:22.04 .
$ ./docker_run.sh
# cd /work/sample_source
# make -f Makefile_for_xc_aarch64
# file sample_aarch64
sample_aarch64: ELF 64-bit LSB executable, ARM aarch64, version 1 (GNU/Linux), statically linked, 
BuildID[sha1]=b79de0a72f4ebc2a1ce8a1b5b27760427a5ee667, for GNU/Linux 3.7.0, not stripped

#3.ビルドしたプログラムの動作確認

##3-1.armv7l

32biit環境上では,64bitでビルドしたプログラムを動作させることはできません.

pi@raspberrypi:~/work/bin $ ./sample_armv7l
Cross Compile has been succeeded!!
pi@raspberrypi:~/work/bin $ ./sample_aarch64
-bash: ./sample_aarch64: バイナリファイルを実行できません: 実行形式エラー

##3-2.aarch64

64bit環境上では,32bitでビルドしたプログラムを動作させることが可能です.

pi@raspberrypi:~/work/bin $ ./sample_armv7l
Cross Compile has been succeeded!!
pi@raspberrypi:~/work/bin $ ./sample_aarch64
Cross Compile has been succeeded!!

#4.さいごに

仮想環境上でクロスコンパイル環境を構築しておくと,ホストPCの置き換えやN増し,クロスコンパイル環境間の競合などを気にしなくてよい為,メリットは多いと思います.
なお,Raspberry Piのセットアップは,Raspberry Pi Imagerを使用してSDカードに書き込むだけですので,本記事では割愛しました.

#5.関連リンク

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?