Monday, September 2, 2013

Assembly Calculator + Source

Hello everyone,

After a long hassle, I began learning Assembly; I must say it is very challenging and it is definitely worth it.

Here is the source:
Code:
.data
    Hello:
        .asciz "1. Add\n2. Subtract\n3. Divide\n4. Multiplication\nOption:"
    first:
        .asciz "First Number:"
    second:
        .asciz "Second Number:"
    answer:
        .asciz "The answer is: %d\n"
    d:
        .ascii "%d\0"
    int1:
        .int 0
    int2:
        .int 0
    option:
        .int 1
.text

.globl _main

    _main:
        pushl $first
        call _printf
        addl $4, %esp

        pushl $int1
        pushl $d
        call _scanf
        addl $8, %esp

        pushl $second
        call _printf
        addl $4, %esp

        pushl $int2
        pushl $d
        call _scanf
        addl $8, %esp

        pushl $Hello
        call _printf
        addl $4, %esp

        pushl $option
        pushl $d
        call _scanf
        addl $8, %esp

        cmpl $1, option
        jz toadd
        cmpl $2, option
        jz subtract
        cmpl $3, option
        jz divide
        cmpl $4, option
        jz multiplication

        toadd:
        movl int1, %eax
        addl int2, %eax
        pushl %eax
        pushl $answer
        call _printf
        addl $8, %esp        
        jmp end        

        subtract:

        movl int1, %eax
        subl int2, %eax
        pushl %eax
        pushl $answer
        call _printf
        addl $8, %esp
        jmp end        

        divide:
        movl int1, %eax
        movl int2, %ebx
        xorl %edx, %edx
        idivl %ebx
        pushl %eax
        pushl $answer
        call _printf        
        addl $8, %esp
        jmp end        

        multiplication:                
        movl int1, %eax
        movl int2, %ebx
        imull %ebx
        pushl %eax
        pushl $answer
        call _printf
        addl $8, %esp

        end:
        call _getchar
        call _getchar
        ret

How do you assemble it?
Code:
as -o main.o main.s

How do you link it?
Code:
ld main.o -o main.exe -e_main -L"C:\Dev-cpp\lib" -lmsvcrt

Is there an easier method to assemble and link it?
Yes, there is. Open notepad and put this:
Code:
as -o main.o main.s
ld main.o -o main.exe -e_main -L"C:\Dev-cpp\lib" -lmsvcrt
Save it as build.bat[orwhatever.bat] and put it into the same folder as the source. Open the build.bat and it should compile.

1 comment: