Put data, code, and stack into different segments: placing all of these contents in the code segment will undoubtedly make the program appear chaotic and difficult to manage and operate, and is prone to errors, data, code, and stack should be put into different segments, which also reflects the idea of "divide and conquer" in software engineering.
Assume Cs: code, DS: data, SS: Stack
Data Segment
DW 0123 H, 0456 H, 0789 H, 0 abch, 0 defh, 0 fedh, 0 cbah, 0987 H // DW means "Define word ", that is, the formatted font data (the last eight data records) is defined)
Data ends
Stack segmetn
DW 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Stack ends
Code segment
Start:
MoV ax, stack
MoV SS, ax
MoV sp, 20 h
MoV ax, Data
MoV ds, ax
MoV BX, 0
MoV CX, 8
S:
Push [BX]
Add Bx, 2
Loop s
MoV BX, 0
MoV CX, 8
S0:
Pop [BX]
Add Bx, 2
Loop S0
MoV ax, 4c00h
Int 21 h
Code ends
End start
Methods for defining multiple segments: defining data segments and stack segments is the same as defining code segments. They are all: XXX segment; XXX ends;
Reference of segment address: how to access the start address of a segment, addressing is implemented by segment address × 16 + offset address. The label of each segment indicates the segment address, for example, data segment; data indicates the segment address of the Data Segment.
MoV ax, Data
MoV ds, Data
This means that DS points to the first unit in the data segment. Afterwards: mov [0], ax; is the first memory unit that sends the content of ax to the beginning of the data segment. However, we cannot write: mov ds, data; data is actually a segment address and a value, which is equivalent to directly sending the value to DS, which is not allowed.
Note that the so-called data segments, code segments, and stack segments are defined by ourselves to facilitate reading by programmers. The CPU does not know which data segments are, which are code segments, and which are Stack segments. Therefore, data, code, and stack are just a series of labels to improve readability. Assume Cs: code, DS: data, SS: Stack, the CPU knows that CS points to code, DS points to data, and SS points to stack. Therefore, we still need to write in the program:
MoV ax, stack
MoV SS, ax
MoV sp, 20 h
Such commands indicate that the SS points to the stack. Therefore, code, data, and stack can be replaced with other names, but we need to define a readable label during the definition.