1
votes

I made a shared library as the follow:

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

When output.c is the follow, it could work.

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

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

But, when output.c changed as the follow, a error occur.

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

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

This is error message:

/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

I want to know why and how to deal it. Thanks in advance.

1

1 Answers

3
votes

You need to compile output.c as position independent code.

gcc -c -fPIC output.c

In the first version you have not called any library function. But in second one printf is being called. In general, compile all sources with -fPIC if you intend to build a shared library later.