写一段 `cabal` 配置启用 `arm-none-gcc` 工具链。

解读

国内金融、区块链与嵌入式团队常把 Haskell 模型编译到 ARM Cortex-M 固件,面试时考官想确认两件事:

  1. 你能否让 cabal 在“包描述”层面把 arm-none-gcc 当作 C 交叉编译器,而不是默认的 /usr/bin/gcc;
  2. 你能否把 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。

答案

  1. 在项目根新建 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
  1. 在 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
  1. 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,若输出为空则证明 静态链接 成功,符合金融级“零外部依赖”要求。