GNU汇编Hello World程序段错误及编译执行问题求助
32位GNU汇编在WSL Ubuntu中的错误解决
段错误原因
你的汇编代码是32位架构(使用int 0x80系统调用、32位通用寄存器%eax/%ebx/%ecx/%edx),直接用gcc -no-pie hello.s -o hello编译时,默认生成64位可执行文件。64位环境下执行32位指令会触发Segmentation fault,添加.code32无法解决,因为编译器仍以64位为目标编译,指令集不兼容。
链接错误与依赖修复
使用gcc -m32 -no-pie hello.s时出现找不到Scrt1.o等文件,是因为64位系统缺少32位编译依赖,安装gcc-multilib是正确步骤,但之后出现cannot execute binary file: Exec format error,是因为WSL未开启32位程序运行支持,需要补充安装32位运行库:
sudo apt install libc6-i386
正确编译运行32位代码
安装依赖后,重新编译:
gcc -m32 -no-pie hello.s -o hello
执行./hello即可正常输出结果。
适配64位系统的代码改造
如果不想依赖32位环境,可将代码改为64位版本(使用64位系统调用规范):
.data hello_str: .string "Hello, world!\n" .text .globl main .type main, @function main: mov $1, %rax # 64位write系统调用号为1 mov $1, %rdi # stdout文件描述符为1 mov $hello_str, %rsi # 字符串首地址 mov $13, %rdx # 字符串长度(含换行符共13字节) syscall # 触发系统调用 mov $60, %rax # 64位exit系统调用号为60 mov $0, %rdi # 返回值0 syscall .size main, . - main
编译命令无需额外参数,直接执行:
gcc hello.s -o hello ./hello
内容的提问来源于stack exchange,提问作者DeBug
相关产品推荐
相关产品推荐

