AT&T-汇编语言与C语言联合编程

AT&T汇编语言实现输出Hello,world.

文件print.s的内容

.data
output: .ascii "hello,world!\n"
len = . - output


.text
.globl _start
_start:
        movl $len,%edx
        movl $output,%ecx
        movl $1,%ebx
        movl $4,%eax
        int $0x80

        movl $1,%eax
        movl $0,%ebx
        int $0x80

编译该文件的命令是:

as -o print.o print.s
ld -s -o print print.o

如果使用ald程序调试print文件时,需要将调试信息编译到文件中去:

as --gstabs -o print.o print.s
ld -o print print.o

使用ald程序调试print文件的过程是:

ald print
ald> disassemble -s .text
ald> break 0x08048083
ald> run
ald> next
ald> help

教程在此

C语言程序中调用汇编语言中的变量和函数

文件add.s的内容

.data
.globl add1
.globl add2
add1: .int 10
add2: .int 20

.text
.code32
.globl add

/*
0x8(%esp)=b
0x4(%esp)=a
*/

add:
        movl 0x8(%esp),%eax
        movl 0x4(%esp),%ebx
        add %ebx,%eax
        ret

文件add_demo.c的内容

#include<stdio.h>
extern int add(int a, int b);
extern int add1;
extern int add2;

int main()
{
        printf("add is %d\n", add(add1, add2));
        printf("add is %d\n", add(40, 30));
        return 0;
}

文件Makefile的内容

all:add_demo

add_demo: add.o add_demo.o
        gcc -o $@ $^

add.o: add.s
        gcc -o $@ -c $^

add_demo.o: add_demo.c
        gcc -o $@ -c $^

clean:
        rm -f *.o
        rm -f add_demo

在汇编语言中调用C函数库的例子。

.data
output : .ascii "the number is %d\n"

.text
.globl _start
_start:
        pushl $520
        pushl $output
        call printf
        addl $8,%esp
        pushl $0
        call exit

编译指令:

as -o print.o print.s
ld -dynamic-linker /lib/ld-linux.so.2 -lc -m elf_i386 -o print print.o

教程在此

猜你喜欢

转载自blog.csdn.net/xkjcf/article/details/78700396