当我制作共享库时,发生错误

When I make a shared library, a error occur

我做了一个共享库如下:

  1. gcc -c output.c
  2. gcc -shared -fPIC -o liboutput.so output.o

当output.c是follow的时候,就可以了。

//#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: relocation R_X86_64_PC32 against undefined 符号 `puts@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: 最后的链结失败: 错误的值 collect2: error: ld returned 1 exit status

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

您需要将 output.c 编译为与位置无关的代码。

gcc -c -fPIC output.c

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