Skip to content

Splitting your code into multiple files β€” #include, #once

Lorenzi edited this page Jan 22, 2022 · 2 revisions

Sometimes, your source files may get too big and you may want to split them into smaller files. This is where the #include directive can come in handy.

This directive effectively copies the given file's content as source code, merging it into the current file being assembled, kind of like what C compilers do.

For example, suppose this was the main source file:

start:
    lda 0x77

#include "extra.asm"

...and that there were another file named extra.asm in the same directory, with the following contents:

jmp start

The files are effectively merged together. The jmp start in the extra.asm file can naturally see the label defined on the main file. This would be the output:

0x0: 10 77
0x2: 55 00 00

Note that, even though the files are logically merged together, the assembler still tracks their location on the directory tree. If you included a file in a subfolder (like #include "stuff/extra.asm"), other include directives inside the stuff/extra.asm file would be resolved relative to the stuff/ folder.

You can use .. to go up a folder in the hierarchy. For example, you could use #include "../../main.asm". It is prohibited to go up further and out of the folder where the base source file resides.

The #once directive

From v0.11.13 onwards

You can prevent a file from being included twice (and from generating "duplicate declaration" errors) by inserting a #once directive.

Following from the previous example:

main.asm:

start:
    lda 0x77

#include "extra.asm"
#include "extra.asm"

extra.asm:

#once

jmp start

This will effectively only output a single instance of the jmp start instruction.