1 完整代码
c
#include <stdio.h>
int main()
{
printf("Hello, TaiShan-Pi (RK3566)!\n");
#ifdef __aarch64__
printf("I was compiled for ARM64.\n");
#else
printf("I was NOT compiled for ARM64.\n");
#endif
return 0;
}
2 编译程序
在 Ubuntu 中可以执行以下命令编译、执行:
bash
$ gcc hello.c -o hello
$ ./hello
Hello, TaiShan-Pi (RK3566)!
I was NOT compiled for ARM64.
上述命令编译得到的可执行程序 hello 可以在 Ubuntu 中运行,但是如果把它放到泰山派上去,它是无法执行的。因为它是使用 gcc 编译的,是给 PC 机编译的,里面的机器指令是 x86 的。
bash
$ file hello
hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, ..., not stripped
要想给泰山派编译出 hello 程序,需要使用对应的交叉编译工具链。
3 交叉编译
3.1 安装交叉编译工具
(1)在线安装
bash
sudo apt update
sudo apt install gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
安装完成之后可以输入以下命令验证gcc、g++的安装是否成功。
gcc-aarch64-linux-gnu:
bash
$ aarch64-linux-gnu-gcc --version
aarch64-linux-gnu-gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
g+±aarch64-linux-gnu:
bash
$ aarch64-linux-gnu-g++ --version
aarch64-linux-gnu-g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
(2)离线安装
从官网下载软件包后(以gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu为例),要将交叉编译工具的路径添加到系统的 PATH 环境变量中,以便可以在任何地方使用交叉编译工具,可以在shell配置文件中添加以下行(通常是 ~/.bashrc 或 ~/.bash_profile 或 ~/.zshrc,具体取决于使用的shell),注意 PATH= 后的路径为交叉编译工具所在的目录。
- gcc路径
bash
<SDK Directory>/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc
- 打开shell配置文件
bash
vi ~/.bashrc
- 将交叉编译工具的路径添加到系统的PATH环境变量中,将 <SDK Directory> 修改为自己的 SDK 路径
bash
export PATH=$PATH:<SDK Directory>/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu/bin
- 重新加载shell配置文件,使更改生效
bash
source ~/.bashrc
- 使用交叉编译工具编译程序
bash
aarch64-linux-gnu-gcc hello.c -o hello
- 交叉编译成功后,将在当前目录下生成可在开发板运行的可执行文件
bash
$ ls
hello hello.c
$ file hello
hello: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, ..., not stripped
4 运行程序
将 hello 程序上传到开发板,运行程序。
bash
# ./hello
Hello, TaiShan-Pi (RK3566)!
I was compiled for ARM64.