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

NASM修改文本颜色报错:Relocation truncated to fit 求助

Fixing "Relocation truncated to fit" Error in Your NASM DOS Code

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, text line is totally fine: int 10h with ah=13h expects ES:BP to point to the string's start, and you already set ES = DS, so this correctly loads the string's address into BP.
  • Using byte ptr removes 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:34:06