Domanda

These are my C codes simply print “Hello" Message. And I want to make mylib.c as shared library.

[mylib.c]

#include <stdio.h>
int mylib();
int main(){
        mylib();
        return 0;
}
int mylib(){
        printf("### Hello I am mylib #####\n");
        return 0;
}

[drive.c]

#include <stdio.h>
int mylib();
int main(){
        mylib();
        return 0;
}

At the firest I compiled mylib.c with folowing command line to make mylib.o

gcc –fPIC –g –c –Wall mylib.c 

Then tried to make it shared librarly like this

 gcc -shared -Wl,-soname,libmylib.so.1 -o /opt/lib/libmylib.so.1.0.1 mylib.o -lc

And I did ldconfig to update /etc/ld.so.cache

Finaly I compiled drive.c link with mylib but linker showed error

gcc -g -Wall -Wextra -pedantic  -I./ -L./ -o drive drive.c –lmylib

/usr/bin/ld: cannot find –lmylib

Dose someone tell me how can I compile it?

È stato utile?

Soluzione 2

I found this article ld cannot find an existing library.

It works if I change to gcc -g -Wall -Wextra -pedantic -I./ -L/opt/lib -o drive drive.c –l:libmylib.so.1

Altri suggerimenti

In my way, you have to follow some ways to use shared library in C.

At first I have created a header file named "shared_library.h", in this file I have introduced a function named "method" as a function of this library.

The code is following:

/*-------This is starting of shared_library.h file-----------*/
void method();
/*-------------This is ending of shared_library.h file--------*/

Then I have defined the method in another file named "shared_library.c". The definition as in code is:

/*-------------This is starting of shared_library.c file---------*/
#include "shared_library.h"
void method()
{
    printf("Method is called");
}
/*-------------This is ending of shared_library.c file---------*/

And finally, the header "shared_library.h" is ready to use. I use the library in my main C file named "main.c". The contents of "main.c" are as follows:

/*-------------This is starting of main.c file----------------*/
#include <stdio.h>
#include "shared_library.h"
int main()
{
    method();
    return 0;
}
/*-------------This is ending of main.c file----------------\*/
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top