Using NASM with D

From D Wiki
Revision as of 21:35, 6 March 2013 by Drey08 (talk | contribs) (D and NASM on Posix: nasm needs elf switch)
Jump to: navigation, search

Introduction

Even though D has an inline assembler, you can use external assemblers and link with the assembled object files. This page describes using NASM with D, but any other assembler should work as long as it has a compatible object file output.

Here is an example of a sum function implemented in assembly:

sum.asm

global  sum

section .text
sum:
        mov     eax, [esp+4]
        add     eax, [esp+8]
        ret


And here it is used from D:

main.d:

import std.stdio;
extern(C) int sum(int, int);  // C linkage - pass parameters on the stack, return result in eax

void main()
{
    writeln(sum(2, 2));  // should print 4
    assert(sum(2, 2) == 4);
}


The next sections describe how to compile and link the two on various operating systems.

D and NASM on Posix

Using NASM and D on Posix works out of the box. To compile and link the code use:

nasm -felf32 sum.asm
dmd main.d sum.o


GDC users can simply replace dmd with gdc in the command.

D and NASM on Windows

Using DMD

Using NASM and D on Windows is more difficult since DMD outputs OMF object files which are incompatible with NASM's COFF object files. By using the -f obj switch NASM can output compatible OMF object files, but you also need to add a USE32 command in your .data section to force NASM to output 32bit object files. Additionally C functions on Windows traditionally have an underscore prepended to their name.

The modified .asm file then reads:

sum.asm

global  _sum

section .text USE32
_sum:
        mov     eax, [esp+4]
        add     eax, [esp+8]
        ret


To compile and link use:

nasm -f obj sum.asm
dmd main.d sum.obj


Note that the linker (Optlink) might complain if you compile your assembly file with debugging symbols (-g switch).

Using GDC

Unlike DMD, GDC uses COFF object files and the LD linker. The USE32 command is not necessary (but will not interfere). On Windows C functions need to have an underscore prepended to them. The .asm file then reads:

sum.asm

global  _sum

section .text
_sum:
        mov     eax, [esp+4]
        add     eax, [esp+8]
        ret

To compile and link use:

nasm -f win32 sum.asm
gdc -m32 -o main.exe main.d sum.obj