NASM修改文本颜色报错:Relocation truncated to fit 求助
Hey there! I see you're diving into NASM for DOS, and that relocation error is a super common pitfall when working with memory references in 16-bit assembly. Let's break down what's going wrong and fix it up.
The Root Cause
Your error stems from how you're accessing variables in the color_string routine. Take lines like these:
mov bl, color mov dl, x mov dh, y
When you use just the variable name (like color), NASM treats it as the memory address of the variable—this is a 16-bit value in DOS's 16-bit environment. But registers like bl, dl, and dh are only 8-bit wide. Trying to cram a 16-bit address into an 8-bit register is impossible, hence the "Relocation truncated to fit" error.
What you actually want is to load the value stored inside those variables, not their addresses. To do that, use square brackets ([]) to indicate memory indirection, and add byte ptr to explicitly tell NASM you're accessing a single byte (since your variables are defined with db).
Corrected Code
Here's your code with the necessary fixes applied:
section .data text: db "Just some text" ; LENGTH = 14. color: db 181 x: db 0 y: db 0 section .text global _start _start: mov bp, text ; STRING TO DISPLAY. mov cx, 14 ; STRING LENGTH. mov [x], byte 50 mov [y], byte 20 call color_string mov ax,4c00h int 21h color_string: mov ax, ds mov es, ax mov ah, 13h mov bh, 0 mov bl, byte [color] ; Load the byte value stored in 'color' mov dl, byte [x] ; Load the byte value stored in 'x' mov dh, byte [y] ; Load the byte value stored in 'y' int 10h ret
Quick Additional Notes
- The
mov bp, textline is totally fine:int 10hwithah=13hexpectsES:BPto point to the string's start, and you already setES = DS, so this correctly loads the string's address intoBP. - Using
byte ptrremoves ambiguity—critical in 16-bit code where size isn't always obvious to the assembler.
With these changes, your code should compile without the relocation error and correctly display the colored text at your specified (x,y) position in DOS.
内容的提问来源于stack exchange,提问作者Green Eagle

