DEV Community

drake
drake

Posted on • Edited on

rust构建openwrt armv7l 程序(跨平台实现的最简单方式)

早期写过一个版本,但是有点繁琐,操作起来容易不成功,而且跨平台性不好

下面是更为简单的实现方式


  • 1、安装rust跨平台使用的交叉编译第三方工具cross github地址

该工具是基于Docker的,所以你的编译环境得有Docker,原理上该工具是对于不同的target有不同的匹配docker镜像,镜像内配置了所需要的一切环境;通过--target 参数来自动匹配拉取镜像,在镜像内完成构建,并将构建结果输出到镜像外部

cargo install cross --git https://github.com/cross-rs/cross
Enter fullscreen mode Exit fullscreen mode
  • 2、使用。安装完直接使用,不需要配置任何其他的东西

使用上和cargo一样,几乎没有区别,直接将cargo换成cross就行

# (ONCE PER BOOT, on Linux)
# Start the Docker daemon, if it's not already running using systemd
# on WSL2 and other systems using SysVinit, use `sudo service docker start`.
$ sudo systemctl start docker

# MAGIC! This Just Works
$ cross build --target aarch64-unknown-linux-gnu

# EVEN MORE MAGICAL! This also Just Works
$ cross test --target mips64-unknown-linux-gnuabi64

# Obviously, this also Just Works
$ cross rustc --target powerpc-unknown-linux-gnu --release -- -C lto
Enter fullscreen mode Exit fullscreen mode
  • 3、编译适配 openwrt armv7l 的程序

编译相当耗时,macos M2 芯片花了8分多钟,是真的慢啊

cross build --target=armv7-unknown-linux-musleabihf --release
Enter fullscreen mode Exit fullscreen mode
  • 4、发布程序

比如代码项目的目录名为subscribe_update

Image description

编译目标程序名称为subscribe

Image description

那么编译好的文件在目录:
/subcribe_update/target/armv7-unknown-linux-musleabihf/release/subscribe

  • 5、部署问题。部署执行程序的时候发现,程序需要读取某个文本文件来加载配置,但是该文件并没有被编译到可执行文件内,就导致了程序报错(找不到可读取的文件)

  • 6、为解决第5点问题,将文本文件改为.rs文件,将配置内容定义为rust的常量

Image description

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay