Making a shared object.

I'm having troubles creating a simple so, and I can't figure out why. I've spent a few hours reading, but no one ever seems to explain the basics. Could someone please explain what I'm doing wrong?

This is my SO project:
1
2
3
4
5
6
7
8
9
10
test.c
  #include <stdio.h>
  void test() { printf("dynamic function"); }
test.h
  void test();
makefile
  all : test.o
          gcc -shared -o libtest.so test.o
  test.o : test.c
          gcc -c -o test.o test.c


First I make, then copy the .h and .so to my next project's root folder which contains
1
2
3
4
5
6
7
8
main.c
  #include "test.h"
  int main() { test(); return 0; }
makefile
  all : main.o
          gcc -o main main.o -L./libtest.so
  main.o : main.c
          gcc -c -o main.o main.c


When I run make on this folder I get:
$ make
gcc -c -o main.o main.c
gcc -o main main.o -L./libtest.so
main.o:main.c:(.text+0xe): undefined reference to `test'
main.o:main.c:(.text+0xe): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `test'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: all] Error 1


I've read about using gcc -o main main.o -L. -llibtest.so but then I get
$ make
gcc -c -o main.o main.c
gcc -o main main.o -L. -llibtest.so
/usr/bin/ld: cannot find -llibtest.so
collect2: error: ld returned 1 exit status
make: *** [makefile:2: all] Error 1


I've also read that I may be missing LD_LIBRARY_PATH, but that sounds like a runtime issue which I haven't gotten to yet.

I had guessed that I hadn't exported the symbols, but I was able to find my entry point with nm -g libtest.so.
Last edited on
After getting frustrated with this, I decided to try a different OS.

I was building all of that in a Cygwin environment. I just installed a fresh Arch Linux VM with only the base, base-devel, and vim packages. Now I don't get any undefined references when I run this, so everything appears to compile fine.

Now when I run my result, I get no output. That means that the SO was never actually called.

I tried the following, but I don't get any output. So something still isn't working.
1
2
export LD_LIBRARY_PATH=/home/stew/app
./main
Run ldd on your executable. That should tell you if you have it linked or not.
Fixed it. There were two problems:

1) I needed -fpic in the test.o recepie.
2) -L. -llibtest.so should have been -L -ltest
Way to go! I use both cygwin and Linux at home -- did you get this running on cygwin?
Topic archived. No new replies allowed.