NASM编译汇编代码出现地址大小组合无效等错误的原因咨询
mov Instructions Hey there, let's break down exactly why you're hitting these errors with your mov instructions involving rbp. The root cause almost always boils down to a mismatch between your assembly code's addressing mode and the register/operand sizes you're using, and here's the breakdown:
1. You're Missing a BITS Directive (Most Likely Culprit)
NASM defaults to 16-bit real mode if you don't explicitly tell it otherwise. The rbp register is a 32-bit extended register—and in 16-bit mode, you can't use 32-bit registers like rbp as base pointers for memory addressing. 16-bit mode only allows bx, bp, si, or di as base registers, with strict combinations (like [bx+si] but not [rbp]).
All the instructions you listed:
mov [rbp], eaxmov [rbp - 4], eaxmov edi, [rbp]- ...and the rest are fully valid in 32-bit or 64-bit protected mode. The error pops up because NASM is trying to parse them as 16-bit code, where
rbpisn't a valid base register for memory access.
Fix: Add a BITS Directive at the Top of Your Code
Specify the correct mode for your target program:
- For 32-bit x86 code:
BITS 32 ; Rest of your code here - For 64-bit x86_64 code:
BITS 64 ; Rest of your code here
Make sure your NASM compile command matches too—use -f elf32 for 32-bit output, or -f elf64 for 64-bit.
2. Rare Case: Accidental Address/Operand Size Prefixes
If you already have a BITS directive set, double-check for unintended prefixes that force a different address size. For example, an addr16 prefix in 32-bit mode would tell NASM to treat memory addresses as 16-bit, but using rbp (a 32-bit register) would create a conflict. Look for any stray db 0x67 (the addr16 prefix byte) in your code that might be messing things up.
3. Quick Validation Test
To confirm it's the mode issue, try compiling a minimal test snippet:
BITS 32 section .text global _start _start: mov [rbp], eax mov [rbp - 4], eax mov edi, [rbp] mov esi, [rbp - 4] mov edi, [rbp - 8] mov [rbp - 8], eax
This should compile without errors using nasm -f elf32 test.asm—if it does, your original code's problem was definitely missing the BITS directive.
内容的提问来源于stack exchange,提问作者Bennett




