Author Topic: Compiling an assembly program with NASM  (Read 14645 times)

Offline Bahar

  • New Member
  • Posts: 1
Compiling an assembly program with NASM
« on: June 16, 2016, 07:49:21 PM »
Hi

I have very simple assembly code in NASM:

section .text
 global main   ;must be declared for linker (ld)
main:          ;tells linker entry point
 mov edx,len   ;message length
 mov ecx,msg   ;message to write
 mov ebx,1     ;file descriptor (stdout)
 mov eax,4     ;system call number (sys_write)
 int 0x80      ;call kernel

mov eax,1      ;system call number (sys_exit)
 int 0x80      ;call kernel
section .data
msg db 'Hello, world!', 0xa   ;our dear string
len equ $ - msg               ;length of our dear string

To compile, I have:

nasm -f win32 test.asm -o test.o
ld test.o -o test.exe

By now, there is no problem. But as long as I run:

test or test.exe

A new window opens which says:

A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.

./test, /test does not work at all.
I'm working on win32.

Thanks,





Offline Bryant Keller

  • Forum Moderator
  • Full Member
  • *****
  • Posts: 360
  • Country: us
    • About Bryant Keller
Re: Compiling an assembly program with NASM
« Reply #1 on: June 23, 2016, 09:35:57 AM »
This simple assembly code is written for Linux and won't run on Windows.

Code: (hello.asm) [Select]
extern GetStdHandle
extern WriteConsoleA
extern ExitProcess

section .text
    global main
main:
    push    -11 ; get handle to stdout
    call    GetStdHandle

    push    0 ;
    push    bytesWritten ; bytes written to stdout
    push    len ; message length
    push    msg ; message to write
    push    eax ; file descriptor (stdout)
    call    WriteConsoleA ; write to console

    push    0 ;
    call    ExitProcess ; exit to windows

section .data
msg         db "Hello World!", 13, 10, 0
len         equ $ - msg

section .bss
bytesWritten        resd 1

Then to build you could use:

Code: [Select]
nasm -f win32 hello.asm -o hello.obj
GoLink /console /entry main hello.obj kernel32.dll 

Sorry, i don't use LD under Windows so I'm not sure how the linkage would work out. I know you'd need to use the -e main option, but not sure about linking against the Windows system DLL's directly with LD. My example uses GoLink from Jeremy Gordon's Go Tools for Windows.

About Bryant Keller
bkeller@about.me