32 位操作系统使用汇编调用 c 函数

演示代码

文件名 : hello.s

.section .data
    format: .asciz "Hello, %s!n"
    message: .asciz "World"

.section .text
.global _start

_start:
    push $message
    push $format
    call printf

    addl $8, %esp

    push $0
    call exit

编译方法

gcc 编译汇编

使用这种方法需要_start 改为 main, 因为 gcc 编译器是从 main 函数开始的

gcc -m32 -o hello hello.s

as 编译连接汇编

在 64 位操作系统编译 32 位汇编程序编译上有两种方法:

编译

1、 修改源代码,在源码顶部加上 .code32 指令(不推荐
2、 如果不像修改源代码,则需要修改编译参数

```shell
as --32 -o hello.o hello.s
```
连接
ld -m elf_i386 -I /lib/ld-linux.so.2 -L /usr/lib32/ -o cpuid2 -lc cpuid2.o

64 位操作系统使用汇编调用 c 函数

演示代码

.section .data
    format: .asciz "Hello, %s!n"
    message: .asciz "World"

.section .text
.global _start

_start:
    subq $8, %rsp

    movq $format, %rdi
    movq $message, %rsi
    xorl %eax, %eax
    call printf

    addq $8, %rsp

    movl $60, %eax
    xorl %edi, %edi
    syscall

编译方法

gcc 编译汇编

使用这种方法需要_start 改为 main, 因为 gcc 编译器是从 main 函数开始的
在64位系统中,默认情况下启用 PIE,但在某些情况下,它可能会导致链接错误。因此,我们这里禁用了 PIE。

gcc -no-pie -o hello hello.s

as 编译连接汇编

编译
as -o hello.o hello.s
连接
ld -I /lib/ld-linux-x86-64.so.2 -L /usr/lib64/ -o hello -lc hello.o

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注