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

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.

主站蜘蛛池模板: 三穗县| 仪征市| 鸡西市| 邓州市| 酉阳| 淳安县| 鲜城| 巴马| 普宁市| 温州市| 雷波县| 永丰县| 吉林市| 改则县| 白城市| 镇坪县| 当阳市| 平邑县| 子长县| 靖宇县| 瓮安县| 菏泽市| 临潭县| 海宁市| 桓仁| 仙居县| 黑山县| 深圳市| 务川| 南京市| 雷波县| 岗巴县| 科技| 宣城市| 永平县| 河曲县| 深州市| 柘荣县| 江门市| 台州市| 蛟河市|