A library has no memory space on its own as it is not a running process. The concept of a shared library is to have shared copy of the code instructions but not of any data used or generated by that code.
so for example if your library is designed to manage a dynamically allocated structure:
object.h
struct object_struct {
char *name;
int foo;
int bar;
};
typedef struct object_struct * object_t; /* opaque pointer */
object_t new_object (char *name, int foo, int bar);
void delete_object(object_t);
int dump_object(object_t);
object.c
#include <stdio.h>
#include "object.h"
object_t new_object (char *_name, int foo, int bar) {
object_t _p = malloc(sizeof(object_t);
if (!_p)
return NULL;
_p->foo = foo; _p->bar = bar;
_p->name = strdup(_name);
return _p;
}
void delete_object(object_t p) {
if(_p->name)
free(_p->name);
if(_p)
free(_p);
}
int dump_object(object_t p) {
FILE * fp = fopen(p->name, "w");
if ( !fp )
return -1;
fprintf(fp, "foo: %d\nbar: %d\n", p->foo, p->bar);
fclose(fp);
return 0;
}
And you have two programs consumer1.c and consumer2.c that use that library object as under:
consumer1.c
#include "object.h"
int main() {
object_t o = new_object("consumer1.txt", 1, 2);
dump_object(o);
delete_object(o);
return 0;
}
consumer2.c
#include "object.h"
int main() {
object_t o = new_object("consumer2.txt", 1, 2);
dump_object(o);
delete_object(o);
return 0;
}
for all intents and purposes, these two programs of the object library WILL NOT have any common data or common memory or common space.
P.S.: assuming gcc and gnu make, here is a make file for you to test it all out.
Makefile
default: libobject.a consumer1 consumer2
.c.o: %.c
$(CC) -c -o $@ $<
libobject.a: object.o
$(AR) r $@ object.o
object.o: object.c object.h
consumer1 consumer2: [email protected] libobject.a
$(CC) -o $@ [email protected] -L. -lobject
P.P.S: This is presented as JUST a guide! I haven't tested the code here AT ALL, hopefully it all works without a hitch however, take it with a grain of salt and if i've made syntactical error please fix appropriately.