首页 文章

当我创建共享库时,会发生错误

提问于
浏览
1

我创建了一个共享库,如下所示:

  • gcc -c output.c

  • gcc -shared -fPIC -o liboutput.so output.o

当output.c如下所示,它可以工作 .

//#include "output.h"
#include <stdio.h>

int output(const char* st) {
    return 1+2;
}

但是,当output.c按照以下方式更改时,会发生错误 .

//#include "output.h"
#include <stdio.h>

int output(const char* st) {
    printf("%s\n", st);
    return 1+2;
}

这是错误消息:

/ usr / bin / ld:output.o:重定位R_X86_64_PC32对未定义的符号`puts @@ GLIBC_2.2.5'在制作共享对象时不能使用;用-fPIC / usr / bin / ld重新编译:最后的链结失败:错误的值collect2:错误:ld返回1退出状态

我想知道为什么以及如何处理它 . 提前致谢 .

1 回答

  • 2

    您需要编译 output.c 作为位置无关代码 .

    gcc -c -fPIC output.c

    在第一个版本中,您没有调用任何库函数 . 但在第二个 printf 被称为 . 通常,如果您打算稍后构建共享库,请使用 -fPIC 编译所有源 .

相关问题