2012-12-16 43 views
3

我想从c调用汇编函数,但我不断收到错误。调用汇编函数从c

.text 
    .globl integrate 
    .type integrate, @function 
integrate: 
    push %ebp 
    mov %esp, %ebp 
    mov $0,%edi 
start_loop:     
    cmp %edi,1024   
    je loop_exit 
    mov 8(%ebp),%eax   
    mov 12(%ebp),%ecx   
    sub %eax,%ecx    
    add %edi,%ecx 
    incl %edi     
    jmp start_loop    
loop_exit:     
    movl %ebp, %esp 
    popl %ebp 
    ret 

这是我的汇编函数,文件名为integrate.s。

#include <stdio.h> 

extern int integrate(int from,int to); 

void main() 
{ 
    printf("%d",integrate(1,10)); 
} 

继承人我的c代码。

function.c:5:6: warning: return type of ‘main’ is not ‘int’ [-Wmain] 
/tmp/cciR63og.o: In function `main': 
function.c:(.text+0x19): undefined reference to `integrate' 
collect2: ld returned 1 exit status 

每当我试图编译我的代码用gcc -Wall function.c -o功能,它给“未定义参考整合” error.I也试图从C添加链接到integrate.s文件,像

#include<(file path)/integrate.s> 

,但它没有工作作为well.Btw什么汇编代码是干什么并不重要,现在我只是想从C successfully.Can任何调用函数帮助我一下解决这个问题?

+0

小丑的答案应该让你的程序不是至少崩溃。你应该标记他的答案。我正在考虑发布完整的汇编代码,但不知道程序集应该做什么,我真的不能做比他的回答更多的东西。 –

回答

4

警告:“主”返回类型不是“诠释”

意味着“主”的返回类型不是“诠释” ......将其更改为int,则:

int main() 
{ 
} 

另外,为了解决所述接头错误,调用GCC作为

gcc -o myprog main.c integrate.s 

一个这应该工作。

+0

它像'gcc mprog main.c integrate.s -o out'一样工作。但是这次它说分割'fault:core dumped'。这与汇编函数中的错误有关吗? –

+0

@AliU。它仍然是。 (为什么你多次发表此评论?) – 2012-12-16 13:04:20

+0

它仍然是?你的意思是汇编函数的错误?(误将它错误地删除了,对不起。) –

6

我看到以下问题与代码:

  • 调用约定强制要求必须保留的edi
  • cmp %edi,1024值使用1024作为地址,可能会发生故障。你想cmp $1024,%edi与立即数
  • 你重装从参数eaxecx每次迭代,所以你执行计算没有影响比较
  • 你似乎没有把任何明智的返回值到eax(它会返回通过的from的值)

即使“汇编代码做的事情并不重要”,前两点也适用。

3

不知道你是否已经解决了这个问题,但这里是我如何做到这一点的。

编译时一定要添加这两个文件:$gcc main.c print_msg.s -o main

为了自身运行汇编文件:其次$ld print_msg.o -e print -o print_msg$as print_msg.s -o print_msg.o。请注意,如果您只想从C文件运行它,则不需要。

汇编文件: print_msg.s

# A program to be called from a C program 
# Declaring data that doesn't change 
.section .data 
    string: .ascii "Hello from assembler\n" 
    length: .quad . - string 

# The actual code 
.section .text 
.global print 
.type print, @function    #<-Important 

print: 
    mov  $0x1,%rax    # Move 1(write) into rax 
    mov  $0x1,%rdi    # Move 1(fd stdOut) into rdi. 
    mov  $string,%rsi   # Move the _location_ of the string into rsi 
    mov  length,%rdx    # Move the _length_ of the string into rdx 
    syscall       # Call the kernel 

    mov  %rax,%rdi    # Move the number of bytes written to rdi 
    mov  $0x3c,%rax    # Move 60(sys_exit) into rax 
    syscall       # Call the kernel 

那么C文件:main.c

extern void print(void); 

int main(void) 
{ 
    print(); 
    return 0; 
}