5.1 Multiple Source Files and Shared Access

Your assembly program can be split into as many source files as required. Doing so will make the source code easier to manage and navigate, but there are steps you must take to share objects and routines between modules, and your code will need to take into account where routines in other modules might ultimately be located.

To access an object or routine define in another source file, there are two steps that need to be followed. First, when you define the object or routine, you must tell the linker to allow the symbol (label) to be globally accessible. This is done using the GLOBAL directive. Next, you must declare the same symbol in every other file that needs to access it to inform the linker that this symbol is linked to a definition in another module. This can be done using either the GLOBAL or EXTRN directive.

In the full example program shown in this chapter, file_1.S contains the definition for the object count, which is essentially a label associated with reserved storage space, as shown below.
GLOBAL count

PSECT  udata_shr
count:
	DS	1                    ;1 byte in common memory

As count must be accessible from other modules, a GLOBAL count directive was used in addition to the symbol's definition, as shown above, to tell the linker that declarations of the same symbol in other modules can link to the definition in this module.

In file_2.S, another GLOBAL count directive was used to declare the symbol and link this with the definition of count that the linker will ultimately find in the file_1.o module. You may prefer to use the EXTRN count directive to perform this function. This directive performs a similar task to GLOBAL, but it will trigger an error if the directive appears in the same module that contains the symbol's definition.

The same mechanism is used for symbols used by routines that need to be accessible from more than one module. In this example, the code in file_2.S contains a GLOBAL storeLevel directive to allow the symbol to be referenced from outside that module, and file_1.S contains the same directive to link the storelevel symbol in that module with its definition in the other. Again, an EXTRN storeLevel directive could have been used in file_1.S to ensure the symbol is defined in the module you expect.