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:
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?
You need to place -l
options on the end of linker invocation command line:
gcc -o program -L. mymain.o -lmyclib
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With