我在链接 2 个目标文件时遇到问题,其中一个是从汇编语言源文件生成的,另一个是从 C 源文件生成的。
C源代码:
//main2.c
extern int strlength(char *);
int main(){
char * test = "hello";
int num = strlength(test);
return num;
}
汇编源代码:
#strlength.s
.include "Linux32.s"
.section .text
.globl strlength
.type strlength, @function
strlength:
pushl %ebp
movl %esp, %ebp
movl $0, %ecx
movl 8(%ebp), %edx
read_next_byte:
movb (%edx), %al
cmpb $END_OF_FILE, %al
jle end
incl %edx
incl %ecx
jmp read_next_byte
end:
movl %ecx, %eax
popl %ebp
ret
当我像这样使用'gcc'编译和运行时:
gcc main2.c strlength.s -m32 -o test
./test
echo $?
我得到 5 这是正确的。但是,当我单独编译/组装然后像这样与'ld'链接时:
as strlength.s --32 -o strlength.o
cc main2.c -m32 -o main2.o
ld -melf_i386 -e main main2.o strlength.o -o test
./test
我得到一个分段错误。这是什么原因造成的?我没有 100% 正确地遵循 C 调用约定吗?