Using Code Segments

A code segment is one or more bytes of machine instructions. It represents all or part of an application's program instructions. A code segment is never larger than 64K.

IMPORTANT:

You must not store writeable data in code segments; writing to a code segment causes a general protection fault when your application runs in protected mode. Windows will, however, allow you to store read-only data, such as a jump table, in a code segment.

Every application has at least one code segment. For example, the sample applications described in previous chapters have one and only one code segment. You can also create an application that has multiple code segments. In fact, most Windows applications have multiple code segments. Using multiple code segments lets you reduce the size of any given code segment to the number of instructions needed to carry out some task. If you also make these segments discardable, you effectively minimize the memory requirements of your application's code segments.

When you create medium- or large-model applications, you are creating applications that use multiple code segments. Medium- and large-model applications typically have one or more source files for each segment. Compile each source file separately and explicitly name the segment to which the compiled code will belong. Then link the application, defining the segments' attributes in the application's module-definition file.

To define a segment's attributes, use the SEGMENTS statement in the module-definition file. The following example shows definitions for three segments:

SEGMENTS

PAINT_TEXT MOVABLE DISCARDABLE

INIT_TEXT MOVABLE DISCARDABLE

WNDPROC_TEXT MOVABLE DISCARDABLE

You can use the CODE statement in the module-definition file to define the default attributes for all code segments. The CODE statement defines attributes for any segments that are not explicitly defined in the SEGMENTS statement. The following example shows how to make all segments not listed in the SEGMENTS statement discardable:

CODE MOVABLE DISCARDABLE

If you use discardable code segments in your application, you need to balance discarding with the number of times the segment may be accessed. For example, the segment containing your main window function should probably not be discardable since Windows calls the function often. Since a discarded segment has to be loaded from disk when needed, the savings in memory you may realize by discarding the window function may be offset by the loss in performance that comes with accessing the disk often.

NOTE:

In a library, all code segments must be both movable and discardable. If a library's module-definition file specifies that a code segment is movable but not discardable, Windows will make that code segment discardable instead.