calling assembly function from c

ε祈祈猫儿з 提交于 2019-11-28 00:13:13

I see the following problems with the code:

  • calling convention mandates you must preserve the value of edi
  • cmp %edi,1024 is using 1024 as address and will probably fault. You want cmp $1024,%edi for comparing with an immediate number
  • you are reloading eax and ecx from the arguments each iteration so the calculation you perform has no effect
  • you don't seem to put any sensible return value into eax (it will return the value of from that was passed in)

The first two points apply even if "what assembly code is doing is not important".

warning: return type of ‘main’ is not ‘int’

means that the return type of ‘main’ is not ‘int’... Change it to int, then:

int main()
{
}

Also, to solve the linker error, invoke GCC as

gcc -o myprog main.c integrate.s

and that should work.

Not sure if you have solved this or not, but here is how I have done this.

When compiling make sure to add both files: $gcc main.c print_msg.s -o main

To run the assembler file on its own: $as print_msg.s -o print_msg.o followed by $ld print_msg.o -e print -o print_msg. Note that this is not required if you only want to run it from your C file.

The assembler file: 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

then the C file: main.c

extern void print(void);

int main(void)
{
    print();
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!