7

I am trying to compile a simple C program in Linux with a shared library.

I have all together in the same folder the following files:

mymain.c

 #include "myclib.h"
 int main() {
   func();
   return 0;
}

myclib.h

 void func();

myclib.c

#include <stdio.h>
void func() {

   printf("hello world!!!!!!!!!!!!\n");

} 

Then I followed these steps:

  • gcc -c fPIC myclib.c (create memoryaddress independent objectfile)

    which produces: myclib.o

  • gcc -shared -fPIC -o libmyclib.so myclib.o (create shared library)

  • gcc -c mymain.c (creates an object file out of main.c)

So far so good - then I have the following files ready:

  • main.o
  • libmyclib.so

So I try to create a program out of this syntax:

gcc -o program -lmyclib -L. mymain.o

(I guess the prefix lib from libmyclib should be replaced with an l?)

But I get the error message from the gc-compiler:

 *mymain.o: In function `main':
 mymain.c:(.text+0xa): undefined reference to `func'
 collect2: error: ld returned 1 exit status*

I have also tested this syntax:

gcc -o program mymain.c -L -lmyclib -Wl,-rpath,.

Then I get the following error:

 /usr/bin/ld: cannot find -lmyclib.so
 collect2: error: ld returned 1 exit status

What am I doing wrong in these two implementations? How do I compile this program to an executable using shared library?

Community
  • 1
  • 1
java
  • 1,165
  • 1
  • 25
  • 50
  • Change `gcc -o program -lmyclib -L. mymain.o` to `gcc -o program mymain.o -lmyclib -L.` – Paul R Apr 20 '15 at 12:44
  • @PaulR The `-k` options need to go last. – fuz Apr 20 '15 at 12:45
  • @FUZxxl: I don't think so (assuming you mean `-L` ?) - see: http://stackoverflow.com/questions/5817269/does-the-order-of-l-and-l-options-in-the-gnu-linker-matter – Paul R Apr 20 '15 at 13:10
  • @PaulR I meant `-l`; sorry, that was a typo. – fuz Apr 20 '15 at 13:47
  • @FUZxxl: indeed - the main point though was that the order of the `-L` and `-l` options don't matter - see the answer I linked to. The only thing that matters is the order of the object files and libraries. – Paul R Apr 20 '15 at 13:56

1 Answers1

7

You need to place -l options on the end of linker invocation command line:

gcc -o program -L. mymain.o -lmyclib
fuz
  • 88,405
  • 25
  • 200
  • 352
  • thanks it works!!! but now when I execute program with ./program I get the error message: **error while loading shared libraries: libmyclib.so: cannot open shared object file: No such file or directory** . But I will accept this answer in a couples of minutes :-) – java Apr 20 '15 at 12:51
  • Wouldn't you need to change LD_PRELOAD to load a shared object located outside the predefined directories? – mcleod_ideafix Apr 20 '15 at 12:53
  • yes - i guess it looks in usr/lib or something? – java Apr 20 '15 at 12:54