You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ARMv8汇编函数编译报错:GCC对每行指令均抛出错误

问题描述

在Windows的WSL环境下使用GCC编译包含ARM汇编函数的代码时,汇编函数f的每一行指令都报错。此前在树莓派上用类似Makefile可以正常编译,想确认是否是WSL环境导致的问题。

主函数代码(main.c)

#include <stdio.h>

extern long long int f(int a, int b);

int main() {
    long long int x = f(3, 2);
    printf("Value of x = %lld\n", x);
    return 0;
}

汇编函数代码(question_4.S)

// Keep local variable b in X19;
// 
// Assume n and k are passed in X0 and X1 respectively and that the result is returned in X0.

.section .text
.global f

f:
    SUB SP, SP, #24         //Clearing space in the SP
    STUR X30, [SP, #16]     //Storing the LR in the SP
    STUR X19, [SP, #8]      //Storing b in the SP
    ADD X19, X1, #2         //b = k + 2
    CMP X0, #0              //Comparing if (n == 0)
    B.NE else               //Goes to else if false
    MOV X19, #8             //k = 8
    ADD SP, SP, #8          //Adding 8 as we don't use the SP to store X9 in this case
    B end                   //Goes to end

else:
    MOV X9, X0              //Storing n in X9
    STUR X9, [SP, #0]       //Storing X9 in the SP
    SUB X0, X0, #1          //n = n - 1
    ADD X1, X1, #1          //k = k + 1
    BL f                    //Calling recursive function
    LDUR X9, [SP, #0]       //Loading X9 from the SP
    ADD SP, SP, #8          //Removing space for X9 from the SP
    LSL X9, X9, #2          //n = n * 4
    ADD X19, X19, X9        //b = b + 4*n
    ADD X19, X19, X0        //b = b + 4*n + f()

end:
    ADD X0, X19, X1         //Stores b + n into X0
    LDUR X19, [SP, #0]      //Loading X19 from the SP
    LDUR X30, [SP, #8]      //Loading X30 from the SP
    ADD SP, SP, #16         //Removing space for X19 and X30 from the SP
    BR LR                   //Branches to the LR

Makefile代码

TARGET = question_4
CC = gcc
LD = gcc

FLAGS = -g -O0

all: $(TARGET)

clean:
    rm *.o
    rm $(TARGET)

main.o: main.c
    $(CC) $(FLAGS) -c $^ -o $@

question_4.o: question_4.S
    $(CC) $(FLAGS) -c $^ -o $@

$(TARGET): main.o question_4.o
    $(LD) main.o question_4.o -o $@

问题原因与解决方案

核心原因

树莓派是ARM架构(通常为AArch64),系统自带的GCC默认编译ARM指令集代码;而WSL默认运行在x86_64架构的Windows主机上,默认GCC针对x86_64指令集,无法识别SUB SP, SP, #24、STUR这类ARM汇编指令,因此全量报错。

解决方案

  1. 安装ARM交叉编译工具链:以Ubuntu系WSL为例,执行以下命令安装AArch64交叉编译器:
    sudo apt update
    sudo apt install gcc-aarch64-linux-gnu
    
  2. 修改Makefile:将编译器替换为交叉编译工具:
    CC = aarch64-linux-gnu-gcc
    LD = aarch64-linux-gnu-gcc
    
  3. 编译与运行:执行make完成编译,若需在WSL中运行ARM程序,需安装QEMU模拟器:
    sudo apt install qemu-user
    ./question_4
    

内容的提问来源于stack exchange,提问作者Bhavesh Saravanakumar Chitrade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:43:17