[英]Getting length of string in NASM with strlen call
我的目标是执行以下操作:
1)编写一个nasm代码,通过从C调用strlen来计算字符串的长度
2)在C中调用此函数以打印提供的字符串的长度
验证码:
;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长度-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
您覆盖getLength.o
从NASM与gcc -c length.c -o getLength.o -m32
。 只需为GCC的输出取另一个名字即可:
GCC非常聪明,您可以折叠第2步和第3步:
2 + 3。 gcc length.c getLength.o -o length -m32
您忘记传递参数给strlen
然后再清除堆栈:
getLength:
push ebp ;save the old base pointer value
mov ebp,esp ;base pointer <- stack pointer
mov eax,[ebp+8] ;first argument
push eax ; first argument onto the stack
call strlen ; call our function to calculate the length of the string
add esp, 4 ; clear stack after C-call
mov edx, eax ; our function leaves the result in EAX
pop ebp
ret
剩下一些多余的说明。 请检查,如果您确实需要它们。
从收到的错误来看,似乎您在ASM文件之前而不是您所描述的之后编译了C文件。
为了使事情复杂化,生成的目标文件将具有相同的文件名。 由于您上次编译了ASM文件,因此getLength.o
是已编译的ASM文件。
结果是您试图链接多个名为getLength
函数(来自ASM文件),而根本没有要链接的main
函数。
您可以通过为目标文件使用不同的名称(例如,对于C文件为length.o
和对于ASM文件为getLength.o
)来解决此问题:
gcc -c length.c -o length.o -m32
nasm -f elf32 getLength.asm -o getLength.o
gcc length.o getLength.o -o length -m32
顺便说一句,您的getLength
函数似乎不正确:
strlen
到堆栈。 在调用strlen
之前先push eax
。 strlen
之后将返回值从eax
移到了edx
。 因为eax
已经具有正确的值,所以这不是必需的。 push eax
,所以还需要在strlen
返回之后恢复堆栈指针。 您可以使用add esp, 4
或mov esp, ebp
来完成此操作,但是必须在pop ebp
之前完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.