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

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.

主站蜘蛛池模板: 宜春市| 宝山区| 宜章县| 晋中市| 通化县| 托克托县| 博白县| 南乐县| 嘉善县| 建湖县| 崇文区| 溆浦县| 凉城县| 博乐市| 当阳市| 康保县| 鹿邑县| 东乌珠穆沁旗| 佳木斯市| 绍兴市| 方山县| 宿州市| 阿瓦提县| 昭平县| 宝坻区| 安乡县| 禹州市| 青铜峡市| 南城县| 万山特区| 江都市| 电白县| 天台县| 恩平市| 宝山区| 嘉禾县| 内黄县| 平武县| 张家川| 乌拉特中旗| 漳浦县|