Skip to content
systemcoding.dev
Assembly

Assemble and Link a NASM Program With ld and gcc

Build the same NASM program two ways on Linux x86-64: a freestanding _start binary linked with ld, and a main function linked with gcc against libc.

6 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the GNU, Arm and Intel logos.

A NASM source file is not a program until it passes through two more steps: assembling to an object file and linking to an executable. There are two ways to do the second step on Linux, and they suit two different kinds of program. ld links a freestanding program that makes its own system calls, with nothing but your code in the process. gcc links against the C library, which gives you printf, malloc and a normal main. This post builds the same job both ways with NASM 2.16.03, binutils 2.42 and GCC 14 on x86-64 Linux, shows what each command does, and explains the flags you will meet. The assembler's own manual is at nasm.us.

Step one: assemble

The assembler turns text into an object file. The format flag tells NASM which container to write.

Shell
nasm -f elf64 hello.asm -o hello.o

-f elf64 selects 64-bit ELF, the object format on Linux. -o hello.o names the output; without it NASM picks the source name with .o. Useful additions are -g -F dwarf for debug information, -l hello.lst for a listing with the bytes beside each line, and -Wall to enable the optional warnings. You can check which formats your NASM knows with nasm -hf, and the output on a typical build includes elf32, elf64, macho64, win64 and bin.

An object file is not runnable. It has code and data in sections, a symbol table, and relocations that mark where addresses are still unknown. readelf -h hello.o reports its type as REL (Relocatable file).

Path one: freestanding with ld

A freestanding program has no C runtime. The kernel starts it at the entry symbol, and everything else is your code. Here is the smallest useful one:

hello.asmnasm
bits 64
default rel

global _start

section .rodata
msg:    db "hello from ld", 10
len     equ $ - msg

section .text
_start:
    mov    eax, 1              ; write
    mov    edi, 1              ; stdout
    lea    rsi, [msg]
    mov    edx, len
    syscall

    mov    eax, 60             ; exit
    xor    edi, edi
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

Link it and run it:

Shell
nasm -f elf64 hello.asm -o hello.o
ld hello.o -o hello
./hello
Text
hello from ld

ld hello.o -o hello is the whole link. By default ld looks for the symbol _start, which is why the file exports it with global _start. It places .text and .rodata into loadable segments, assigns addresses starting at 0x401000 for a default non-PIE executable on x86-64, and writes an ELF file. You can see the entry point and the type:

Shell
readelf -h hello | grep -E 'Type|Entry'
file hello
Text
  Type:                              EXEC (Executable file)
  Entry point address:               0x401000
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped

The entry address may differ with your binutils version and linker defaults. The phrase "statically linked" means no shared libraries are involved, and ldd hello reports not a dynamic executable.

Path two: libc with gcc

If the program calls a C library function, it needs the C runtime start-up code, the dynamic loader information and libc itself. The simplest way to get all of that is to let gcc do the final link, and to write main instead of _start. The C runtime's _start runs first, sets up the stack and libc, and calls your main.

greet.asmnasm
bits 64
default rel

global main
extern puts

section .rodata
msg:    db "hello from gcc", 0

section .text
main:
    sub    rsp, 8              ; keep the stack 16-byte aligned for the call
    lea    rdi, [msg]
    call   puts wrt ..plt
    xor    eax, eax            ; return 0
    add    rsp, 8
    ret

section .note.GNU-stack noalloc noexec nowrite progbits
Shell
nasm -f elf64 greet.asm -o greet.o
gcc greet.o -o greet
./greet
Text
hello from gcc

Three things differ from the ld path. The entry symbol is main, and ret returns to libc, which calls exit with the returned value. The stack must be aligned to 16 bytes at the call to puts, because the System V ABI requires it, and on entry to main RSP is 8 bytes off, so sub rsp, 8 realigns it. And the call to puts goes through the PLT, written call puts wrt ..plt, because gcc links a position-independent executable by default on most distributions.

The result is dynamically linked:

Shell
file greet
ldd greet
Text
greet: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=..., for GNU/Linux 3.2.0, not stripped
	linux-vdso.so.1 (0x00007ffd5c1f4000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3e8f800000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f3e8fa2d000)

The addresses and BuildID vary per run and system. The interpreter line is the dynamic loader that maps libc before main starts.

Mixing the two: gcc without the C runtime

You can use gcc as the linker driver and still skip the C start files by naming your own entry point. -nostartfiles removes crt1.o and friends, and -nostdlib also removes libc and libgcc:

Shell
gcc -nostartfiles -nostdlib -static hello.o -o hello-gcc

With -nostartfiles, the entry symbol defaults to _start again, so the freestanding program from path one links under gcc as well. -static asks for no dynamic loader. This route is useful when you want gcc to apply the platform defaults, such as the linker script and hardening flags, while owning the start-up code.

The flags worth knowing

FlagToolEffect
-f elf64nasmobject format for 64-bit Linux
-g -F dwarfnasmemit DWARF debug information for GDB
-l file.lstnasmwrite a listing file
-e symbolldentry symbol, default _start
-o fileld, gccoutput name
-staticld, gccno dynamic linking
-no-piegccfixed-address executable, allows absolute addresses
-pield, gccposition-independent executable
-nostdlibgccdo not link libc or start files
-lcld, gcclink libc, needed with ld alone
-m elf_x86_64ldchoose the emulation, rarely needed on a 64-bit host
-Map=file.mapldwrite a link map with addresses

The link map is the quickest way to see what the linker did. ld -Map=hello.map hello.o -o hello writes a file listing each section, its address and the object that contributed it.

Linking libc with plain ld

You can link against libc using only ld, but it is awkward, because you must name the dynamic loader, the C start files and the libc paths yourself. For this reason people use gcc for it. A sketch for the curious:

Shell
ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 \
   /usr/lib/x86_64-linux-gnu/crt1.o \
   /usr/lib/x86_64-linux-gnu/crti.o \
   greet.o -lc \
   /usr/lib/x86_64-linux-gnu/crtn.o -o greet-ld

The paths differ between distributions and between multiarch layouts, so this command is a template and not portable. If it fails with cannot find -lc, the library directory is missing from the search path; add -L/usr/lib/x86_64-linux-gnu. The reason to know the command is to understand what gcc does for you: add the start files, add -lc, and name the interpreter.

Three errors cover most first-day failures.

Text
ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000

The source lacks global _start, or the entry has a different name. Add the directive, or pass -e main if main is intended.

Text
/usr/bin/ld: hello.o: relocation R_X86_64_32 against `.rodata' can not be used when making a PIE object; recompile with -fPIE

The code used an absolute address, such as mov edi, msg, and gcc linked a PIE. Use RIP-relative addressing, lea rdi, [rel msg], or link with -no-pie.

Text
/usr/bin/ld: warning: hello.o: missing .note.GNU-stack section implies executable stack

Add the .note.GNU-stack section to the source, as the examples do, or the linker marks the stack executable.

A fourth, less visible failure is a segmentation fault on startup of a main-based program, usually from a misaligned stack at a libc call. Check that RSP is 16-byte aligned at every call.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.