用汇编语言编写的c调用函数

标签 c linux gcc assembly

我正在使用 GCC 练习 C 和汇编语言混合编程。发生了这个错误:

1 deng@ubuntu:~/workspace/leos_test$ make
2 ld -o deng c.o asm.o
3 ld: warning: cannot find entry symbol _start; defaulting to 0000000008048074
4 c.o: In function `main':
5 c_and_asm.c:(.text+0x19): undefined reference to `add'
6 c_and_asm.c:(.text+0x2e): undefined reference to `printf'
7 make: *** [deng] Error 1

这是 C 代码:

1 #include<stdio.h>
2 void extern add(int * i);
3 void main(){
4    int i=1;
5    add(&i);
6    printf("%d ",i);
7}

这是汇编语言代码:

1 .globl _add
2 _add:
3 push %bp;
4 mov %sp,%bp;
5 mov 0x4(%bp),%eax;
6 incw (%eax);
7 popw %bp;
8 ret

这是生成文件:

1 deng: c.o asm.o
    2 ld -o deng c.o asm.o
3 c.o:
    4 gcc -o c.o -c c_and_asm.c
5 asm.o:
    6 as -o asm.o c_asm.asm

如有任何建议,我们将不胜感激:)。

最佳答案

将您的 c_asm.asm 文件更改为:

.section .text
.global add
.type add,@function
add:
push %bp;
mov %sp,%bp;
mov 0x4(%bp),%eax;
incw (%eax);
popw %bp;
ret

在你的ld中包含这个参数-lc,最好将文件扩展名更改为.s

关于用汇编语言编写的c调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12984874/

相关文章:

c - 循环获取主机、网络、协议(protocol)和服务数据库中的多个条目

c - 如何在 C 中将 char 指针转换为 float?

linux - 在同一台服务器上安装多个 NFS 的 puppet

linux - 使用 Splunk 模拟安全漏洞

c++ - 模板编译: gcc vs VS2010

c++ - opengl中对象的旋转

c - 为什么 char* 会导致未定义的行为而 char[] 不会?

java - 带有 64 位 JVM 的 32 位库

C 编译器错误 : unknown type name '__evenaccess'

c++ - 为什么 auto_ptr 构造不能使用 = 语法