2012-12-16 41 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; 
}