在Ubuntu中配置适配泰山派的交叉编译环境

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  
  1. 使用交叉编译工具编译程序
bash 复制代码
aarch64-linux-gnu-gcc hello.c -o hello
  1. 交叉编译成功后,将在当前目录下生成可在开发板运行的可执行文件
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.
相关推荐
sorry#20 小时前
top简单使用
linux·运维
半壶清水21 小时前
开源免费的在线考试系统online-exam-system部署方法
运维·ubuntu·docker·开源
QQ__176461982421 小时前
Ubuntu系统创建新用户与删除用户
linux·运维·服务器
永远前进不waiting21 小时前
C复习——1
c语言·开发语言
一路往蓝-Anbo21 小时前
【第13期】中断机制详解 :从向量表到ISR
c语言·开发语言·stm32·单片机·嵌入式硬件
渣渣盟21 小时前
Linux邮件服务器快速搭建指南
linux·服务器·开发语言
6极地诈唬21 小时前
【PG漫步】DELETE不会改变本地文件的大小,VACUUM也不会
linux·服务器·数据库
ArrebolJiuZhou21 小时前
00 arm开发环境的搭建
linux·arm开发·单片机·嵌入式硬件
谷雨不太卷1 天前
Linux_文件权限
linux·运维·服务器
无泪无花月隐星沉1 天前
uos server 1070e lvm格式磁盘扩容分区
linux·运维·uos