What's the difference between equ and db in NASM?

后端 未结 3 1550
谎友^
谎友^ 2020-12-08 07:27
len:  equ  2
len:  db   2

Are they the same, producing a label that can be used instead of 2? If not, then what is the advantage or di

3条回答
  •  感情败类
    2020-12-08 08:04

    The first is equate, similar to C's:

    #define len 2
    

    in that it doesn't actually allocate any space in the final code, it simply sets the len symbol to be equal to 2. Then, when you use len later on in your source code, it's the same as if you're using the constant 2.

    The second is define byte, similar to C's:

    int len = 2;
    

    It does actually allocate space, one byte in memory, stores a 2 there, and sets len to be the address of that byte.

    Here's some psuedo-assembler code that shows the distinction:

    line   addr   code       label   instruction
    ----   ----   --------   -----   -----------
       1   0000                      org    1234
       2   1234              elen    equ    2
       3   1234   02         dlen    db     2
       4   1235   44 02 00           mov    ax     elen
       5   1238   44 34 12           mov    ax     dlen
    

    Line 1 simply sets the assembly address to be 1234, to make it easier to explain what's happening.

    In line 2, no code is generated, the assembler simply loads elen into the symbol table with the value 2. Since no code has been generated, the address does not change.

    Then, when you use it on line 4, it loads that value into the register.

    Line 3 shows that db is different, it actually allocates some space (one byte) and stores the value in that space. It then loads dlen into the symbol table but gives it the value of that address 1234 rather than the constant value 2.

    When you later use dlen on line 5, you get the address, which you would have to dereference to get the actual value 2.

提交回复
热议问题