编译C文件和程序集文件时的链接错误

时间:2014-12-16 16:56:25

标签: c assembly

我有.s(x86汇编语言和语法)文件,.h(标题)文件,带有struct defenition和函数decleration,它们在汇编文件中实现,main.c文件带有函数调用(来自.s)文件)。

当尝试将它们全部编译在一起时,我收到以下错误:

main.o: In function `main':
/home/user/workspace/Assembly/main.c:7: undefined reference to `pstrlen'
collect2: error: ld returned 1 exit status
make: *** [a.out] Error 1

pstring.h:

typedef struct {
    char len;
    char str[255];
    } Pstring;


char pstrlen(Pstring* pstr);

main.c中:

#include <stdio.h>
#include "pstring.h"

int main() {
    Pstring a;
    a.len = 4;
    printf("Length: %d", pstrlen(&a));
    return 0;
}

pstring.s:

    .file   "pstring.s"
    .section    .rodata
invalid_input:  .string "invalid input!\n"


    .text
    .type   pstrlen,    @function
pstrlen:
    pushl   %ebp
    movl    %ebp, %esp

    movl    8(%ebp), %eax   # assign given pstring ptr address to eax
    movzbl  (%eax), %ecx    # set ecx with the value of the first byte (length) of the address at eax
    movl    %ecx, %eax      # set return value as the value at ecx

    ret

    .type   pstrcpy,    @function

生成文件:

a.out: main.o pstring.o
    gcc -m32 -g -o a.out main.o pstring.o

main.o: main.c pstring.h
    gcc -m32 -g -c -o main.o main.c

pstring.o: pstring.s
    gcc -m32 -g -c -o pstring.o pstring.s   

clean:
    rm -f *.o a.out

谢谢。

1 个答案:

答案 0 :(得分:0)

我通过将pstrlen声明为全局来解决问题,如下所示:

    .text
    .globl  pstrlen
    .type   pstrlen,    @function
pstrlen:
    pushl   %ebp
    movl    %ebp, %esp

    movl    8(%ebp), %eax   # assign given pstring ptr address to eax
    movzbl  (%eax), %ecx    # set ecx with the value of the first byte (length) of the     address at eax
    movl    %ecx, %eax      # set return value as the value at ecx

    ret