【发布时间】:2016-01-01 10:24:33
【问题描述】:
我的目标是做到以下几点:
1) 编写一个 nasm 代码,通过从 C 中调用 strlen 来计算字符串的长度
2) 在 C 中调用此函数以打印提供的字符串的长度
Nasm 代码:
;nasm -f elf32 getLength.asm -o getLength.o
segment .text
extern strlen
global getLength
getLength:
push ebp ;save the old base pointer value
mov ebp,esp ;base pointer <- stack pointer
mov eax,[ebp+8] ;first argument
call strlen ; call our function to calculate the length of the string
mov edx, eax ; our function leaves the result in EAX
pop ebp
ret
C 代码:
#include <stdio.h>
#include <string.h>
int getLength(char *str);
int main(void)
{
char str[256];
int l;
printf("Enter string: ");
scanf("%s" , str) ;
//l = strlen(str);
l = getLength(str);
printf("The length is: %d\n", l);
return 0;
}
我尝试编译、链接和运行如下:
1) nasm -f elf32 getLength.asm -o getLength.o
2) gcc -c length.c -o getLength.o -m32
3)gcc getLength.o getLength.o -o length -m32
我得到的错误:
getLength.o: In function `getLength':
getLength.asm:(.text+0x0): multiple definition of `getLength'
getLength.o:getLength.asm:(.text+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../lib32/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status
【问题讨论】: