Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a C program in Linux using shared library [duplicate]

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?

like image 935
java Avatar asked Apr 20 '15 12:04

java


1 Answers

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

gcc -o program -L. mymain.o -lmyclib
like image 152
fuz Avatar answered Oct 16 '22 23:10

fuz