5.3. Changing and Defining Sections


The SECTION directive (((SEGMENT)) is an exactly equivalent synonym) changes which section of the output file the code you write will be assembled into. In some object file formats, the number and names of sections are fixed; in others, the user may make up as many as they wish. Hence SECTION may sometimes give an error message, or may define a new section, if you try to switch to a section that does not (yet) exist.

5.3.2. Standardized Section Names

The Unix object formats, and the bin object format, all support the standardised section names .text, .data and .bss for the code, data and uninitialised-data sections. The obj format, by contrast, does not recognise these section names as being special, and indeed will strip off the leading period of any section name that has one.

5.3.3. The __SECT__ Macro

The SECTION directive is unusual in that its user-level form functions differently from its primitive form. The primitive form, [SECTION xyz], simply switches the current target section to the one given. The user-level form, SECTION xyz, however, first defines the single-line macro __SECT__ to be the primitive [SECTION] directive which it is about to issue, and then issues it. So the user-level directive

        SECTION .text

expands to the two lines

%define __SECT__ [SECTION .text]
        [SECTION .text]

Users may find it useful to make use of this in their own macros. For example, the writefile macro defined in the NASM Manual can be usefully rewritten in the following more sophisticated form:

%macro writefile 2+
        [section .data]
%%str:  db %2
        mov dx,%%str
        mov cx,%%endstr-%%str
        mov bx,%1
        mov ah,0x40
        int 0x21

This form of the macro, once passed a string to output, first switches temporarily to the data section of the file, using the primitive form of the SECTION directive so as not to modify __SECT__. It then declares its string in the data section, and then invokes __SECT__ to switch back to whichever section the user was previously working in. It thus avoids the need, in the previous version of the macro, to include a JMP instruction to jump over the data, and also does not fail if, in a complicated OBJ format module, the user could potentially be assembling the code in any of several separate code sections.