写一段 `cabal` 配置启用 `arm-none-gcc` 工具链。
解读
国内金融、区块链与嵌入式团队常把 Haskell 模型编译到 ARM Cortex-M 固件,面试时考官想确认两件事:
- 你能否让 cabal 在“包描述”层面把
arm-none-gcc当作 C 交叉编译器,而不是默认的/usr/bin/gcc; - 你能否把 flags、extra-lib-dirs、extra-include-dirs、pkg-config 等交叉编译常见参数一次性写对,避免“本地能过、ARM 链接崩”的低级错误。
答不上来会被直接判定为“只会写业务逻辑,不会落地到嵌入式”。
知识点
- cabal 的
build-type: Configure与custom-setup允许在Setup.hs里调用autoconf生成config.sub,从而把CC、LD、AR指向交叉工具链。 - cabal 2.2+ 支持
package.cabal内嵌common节,可用if os(linux) && arch(arm)条件块隔离交叉与本地编译。 - cabal.project 层面可用
program-options把gcc映射到arm-none-gcc,无需写死绝对路径,方便 CI 镜像。 - 国内镜像源(清华、中科大)常把
arm-none-gcc装在/opt/gcc-arm-none-eabi-10/bin,pkg-config 需要额外指定PKG_CONFIG_PATH=/opt/gcc-arm-none-eabi-10/arm-none-eabi/lib/pkgconfig。 - 若用到
cbits中的stm32f4xx_hal.c,必须加cc-options: -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16,否则链接阶段会找不到__aeabi_fadd。
答案
- 在项目根新建
cabal.project,强制把gcc映射到交叉工具链:
-- cabal.project
packages: .
program-options
gcc-location: /opt/gcc-arm-none-eabi-10/bin/arm-none-gcc
ar-location: /opt/gcc-arm-none-eabi-10/bin/arm-none-ar
- 在
package.cabal里用common节集中写交叉编译参数:
common arm
if arch(arm)
cc-options: -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
ld-options: -Wl,--gc-sections -nostartfiles -T link.ld
extra-lib-dirs: /opt/gcc-arm-none-eabi-10/arm-none-eabi/lib
extra-include-dirs: /opt/gcc-arm-none-eabi-10/arm-none-eabi/include
pkgconfig-depends: libstm32f4
executable firmware
import: arm
main-is: Main.hs
c-sources: cbits/stm32f4xx_hal.c
build-depends: base >=4.14 && <5
default-language: Haskell2010
- CI 镜像里一次性导出环境变量,确保 cabal 子进程能继承:
export PATH=/opt/gcc-arm-none-eabi-10/bin:$PATH
export PKG_CONFIG_PATH=/opt/gcc-arm-none-eabi-10/arm-none-eabi/lib/pkgconfig
cabal build --project-file=cabal.project -fembed-firmware
至此,arm-none-gcc 工具链被 cabal 完整识别,本地 x86 与 ARM 固件可在同一仓库共存,切换只需改 --project-file。
拓展思考
- 若团队用 GHC 9.6 的 JavaScript backend 做 Web 端,而 ARM 端仍用 C 交叉编译,可在
cabal.project里写多package *块,分别指定ghc-options: -fwasm32与program-options gcc-location,实现“三端同仓”。 - 国内银行核心系统常把 Haskell 模型编译到 ARM TrustZone 安全核,此时需在
Setup.hs里调用arm-none-gcc生成cmse输入段,再用cabal sdist把签名后的.a一并打包,确保监管审计能重现固件。 - 当面试官追问“如何验证交叉编译后的 ELF 没有动态依赖”,可答:用
arm-none-readelf -d dist-newstyle/build/arm-linux/ghc-*/firmware-*/x/firmware/build/firmware/firmware | grep NEEDED,若输出为空则证明 静态链接 成功,符合金融级“零外部依赖”要求。