How to compile and link MASM32

In this guide you will learn how to compile a MASM assembly file into a Windows executable.

Prerequisites

Before we begin you’re going to need to install MASM32. I’ve written a guide on how to do that. MASM includes the required compiler ml.exe and the linker link.exe. The documentation for each are below.

Once you have MASM installed copy the sample code below and save it as program.asm:

.386
.model flat,stdcall
.stack 4096
.code
main PROC
nop
main ENDP
END main

Our executable will do absolutely nothing. It will be used to test compilation and linking. Let’s do that …

The Not So Easy Way

Some time in the past it was possible to run ml.exe and have it produce an executable. This method has never worked for me for reasons I will discuss in a moment:

ml.exe program.asm 

On my system this produces the following error:

LINK : warning LNK4044: unrecognized option "z2"; ignored

This error occurs because the compiler attempts to compile and link, but if your ml.exe and link.exe versions do not match you will run into this same problem.

The reason is because ml.exe is attempting to pass the /z2 option to link.exe, but the linker doesn’t recognize the option. This is discussed in a bit more detail here.

Fear not my friends, there is a solution!

The Other Way

Instead of expecting ml.exe to call link.exe you can instead compile the assembly into .obj file and call link.exe yourself. An equally simple solution.

You do that like so:

ml.exe /c /coff program.asm
link.exe /subsystem:windows program.obj

The first line compiles the MASM assembly file into an COFF (common object file format) file. The /c option tells ml.exe to not run link.exe. The /coff option is what tells the compiler to generates a COFF file.

The second line runs the linker. The /subsystem:windows option is required and tells the operating system how to run the executable.

Running the 2 commands will compile and link your MASM assembly to produce a Win32 executable. Note the above will not work if you’re using MASM64.

If you have any problems or questions please leave a comment below.


💡 Assembly Language Weekly Newsletter

Every week I publish a newsletter that contains tutorials, tips, tricks and resources related to assembly language. If you would like to receive this newsletter subscribe here: http://eepurl.com/ghximb

Leave a comment