0

I have a main file, which calls a function defined in the shared lib.

// main.c
int main()
{
    int x[2] = {1, 2};
    int y[2] = {3, 4};
    int z[2];
    addvec(x, y, z, 2);
}

The shared library is the following code

// addvec.c

void addvec(int *x, int *y, int *z, int n)
{
    int i;
    for(i = 0; i < n; ++i)
         z[i] = x[i] + y[i];
}

I used gcc -shared -fpic -nostdlib -o libevctor.so addvec.c to make a shared library.

Then I compiled main.c without linking.

gcc -c main.c -o main.o

Finally, I linked these two parts:

ld -rpath=$PWD -dynamic-linker /lib/ld-linux.so.2 -m elf_i386 -e main main.o libvector.so -o prog

Everything works fine so far. However, when I run prog, segmentation fault occurs.

Besides, I used readelf for prog and found the value of addvec in .dynsym is 0:

symbol table '.dynsym' consists of 5 entries:
Num:  value:  Size   Type    Bind   Vis   Ndx   Name
0:   00000000   0     NOTYPE LOCAL  DEFAULT UND
1:   00000000   0     FUNC   GLOBAL DEFAULT UND addvec
2:   0804934c   0     FUNC   GLOBAL DEFAULT 10  __bss_start
....

Did I do anything wrong?

Will Wang
  • 105
  • 1
  • 3
  • 10

1 Answers1

1

Normally you should not use ld (or gold or any other linker) explicitly because invocation line is very target-dependent and fragile. Just link with gcc:

gcc -Wl,-rpath=$PWD -m32 main.o libvector.so -o prog

In your particular case you were probly missing crt object files which handle program startup and libc setup (add -v to see actual ld invocation line).

yugr
  • 19,769
  • 3
  • 51
  • 96