官术网_书友最值得收藏!

Step 2 - let's test

Once ready, let's build our first Assembly program on Linux. Create an Assembly source file named, for example, test.S.

Assembly source files on *nix platforms have the extension .S or .s instead of .asm.

Fill in the following code:

/*
This is a multiline comment.
*/
// This is a single line comment.
# Another single line comment.

# The following line is not a necessity.
.file "test.S"

# Tell GAS that we are using an external function.
.extern printf

# Make some data - store message in data section 0
.data
msg:
.ascii "Hello from Assembly language!xaxdx0"

# Begin the actual code
.text
# Make main() publicly visible
.globl main
/*
This is our main() function.
It is important to mention,
that we can't begin the program with
'main()' when using GAS alone. We have then
to begin the program with 'start' or '_start'
function.
*/

main:
pushl %ebp
movl %esp, %ebp
pushl $msg # Pass parameter (pointer
# to message) to output_message function.
call output_message # Print the message
movl $0, %eax
leave
ret

# This function simply prints out a message to the Terminal
output_message:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
movl 8(%ebp), %eax
movl %eax, (%esp)
call _printf # Here we call printf
addl $4, %esp
movl $0, %eax
leave
ret $4
Prepend printf and main with an underscore ( _) if you are on Windows.

If on Linux, build the code with the following command:

gcc -o test test.S
In order for this code to be compiled correctly on a 64-bit system, as it is written for 32-bit assembler, you should install the 32-bit toolchain and libraries, as well as add the -m32 option, which tells GCC to generate code for a 32-bit platform, with this command:
gcc -m32 -o test test.S
Refer to the documentation of your Linux distro for instructions on how to install 32-bit libraries.

If you're on Windows, change the name of the output executable accordingly:

gcc -o test.exe test.S

Run the executable in the Terminal. You should see the message followed by a new line:

Hello from Assembly language!

As you may have noticed, the syntax of this Assembly source is different from that supported by MASM. While MASM supports what is called Intel syntax, GAS originally supported only the AT&T syntax. However, the support for Intel syntax was added at some point, thus making the life of new adepts significantly easier.

主站蜘蛛池模板: 铜梁县| 醴陵市| 绍兴市| 灵山县| 柯坪县| 丹东市| 资溪县| 德兴市| 和静县| 余江县| 塔河县| 香河县| 沁源县| 盐边县| 新昌县| 咸丰县| 镇巴县| 谷城县| 东乌珠穆沁旗| 福鼎市| 顺义区| 修水县| 霍林郭勒市| 尼勒克县| 神农架林区| 大荔县| 宜兴市| 龙川县| 资源县| 平塘县| 泾川县| 耿马| 东海县| 福安市| 丰顺县| 红安县| 曲沃县| 南康市| 陈巴尔虎旗| 杭锦后旗| 思南县|