ashish
ashish

Reputation: 170

Error while compiling a shared library

Using gcc I am trying to make a shared library on a x86_64 system. The code is

int myglob = 42;

int ml_func(int a, int b)
{
    myglob += a;
    return b + myglob;
}

Compiling it with gcc -c -g code.c -o code.o and then gcc -shared code.o -o libcode.so throws and error!

The error is /usr/bin/ld: libconst.o: relocation R_X86_64_PC32 against symbol 'myglob' can not be used when making a shared object; recompile with -fPIC.

So I tried compiling it with -fPIC flag but it throws the same error.

Note: I am trying to see load time relocation in libraries so I connot use the flag -fPIC.

Upvotes: 1

Views: 927

Answers (2)

dvhh
dvhh

Reputation: 4750

If myglob is not used outside of the code in the library you could specify the static storage class for the variable. A static global variable will be located in the BSS segment.

Example:

static int myglob = 42;

int ml_func(int a, int b)
{
    myglob += a;
    return b + myglob;
}

Upvotes: 0

aebudak
aebudak

Reputation: 699

On x86_64 architecture gcc requires you to use -fPIC (Position Independent Code). This is because relocation type for the symbols rand is of type R_X86_64_PC32. What you could do is use -mcmodel=large which will set the relocation type to R_X86_64_64.

gcc -g -mcmodel=large -c code.c -o code.o
gcc -shared -o libcode.so code.o

Better explained here.

Upvotes: 3

Related Questions