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

如何在GDB中无需类型转换打印并修改GAS汇编变量

问题:GAS汇编变量在GDB中无需类型转换实现打印与修改

我用GAS汇编写了一段寄存器与内存间数据移动的代码:

.section .data
    constant:
        .int 10

.section .text
    .globl _start

_start:
    nop

mov_immediate_data_between_reg_and_mem:
    movl $777, %eax
    movl %eax, constant

exit:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

编译链接生成可执行文件后,用GDB调试时打印修改后的constant变量报错:

Breakpoint 1, 0x08049000 in _start ()
(gdb) si
0x08049001 in mov_immediate_data_between_reg_and_mem ()
(gdb) si
0x08049006 in mov_immediate_data_between_reg_and_mem ()
(gdb) si
0x0804900b in exit ()
(gdb) print constant
'constant' has unknown type; cast it to its declared type

强制类型转换后能正常打印:

(gdb) print (int)constant
$1 = 777

但赋值时,转换类型后仍报错:

(gdb) set (int)constant = 666
Left operand of assignment is not an lvalue.

请问如何无需类型转换实现打印并修改变量?


解决方案

要让GDB自动识别变量类型并支持直接修改,需要从两个方面处理:

1. 编译时生成调试符号

编译汇编代码时添加-g参数,生成完整的调试信息,让GDB能关联变量的符号与类型:

as -g -o test.o test.s
ld -o test test.o

2. 用GAS伪指令显式声明变量类型

在.data段中,给constant添加.type和.size伪指令,明确标注变量的类型和字节大小:

.section .data
    constant:
        .int 10
        .type constant, @object  # 声明该符号为对象类型
        .size constant, 4        # 指定变量大小为4字节(对应int类型)

修改后的完整代码:

.section .data
    constant:
        .int 10
        .type constant, @object
        .size constant, 4

.section .text
    .globl _start

_start:
    nop

mov_immediate_data_between_reg_and_mem:
    movl $777, %eax
    movl %eax, constant

exit:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

重新编译后,GDB就能直接识别constant的类型,无需强制转换即可打印和修改:

(gdb) print constant
$1 = 777
(gdb) set constant = 666
(gdb) print constant
$2 = 666

内容的提问来源于stack exchange,提问作者yaratamin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:05:02