Reading time: 2 min
libhello.h:
#ifndef LIBHELLO_H
#define LIBHELLO_H
void say_hello();
#endif // LIBHELLO_H
libhello.c:
#include <stdio.h>
void say_hello() {
puts("Hello, I am a shared library");
}
test.c:
#include <stdio.h>
#include "libhello.h"
int main() {
say_hello();
return 0;
}
CC = gcc
CFLAGS = -Wall -Werror
TARGETS = test1 test2 test3
all: $(TARGETS)
lib: libhello.c
$(CC) -c $(CFLAGS) -fpic $<
$(CC) -shared -o libhello.so libhello.o
test1: test.c lib
$(CC) -L. $(CFLAGS) -o $@ $< -lhello
test2: test.c lib
$(CC) -L. -Wl,-rpath=. $(CFLAGS) -o $@ $< -lhello
test3: test.c lib install
$(CC) $(CFLAGS) -o $@ $< -lhello
@#ldd test_libhello3 | grep hello
install:
sudo install -m755 ./libhello.so /usr/lib
sudo ldconfig
@#ldconfig -p | grep hello
uninstall:
sudo rm -f /usr/lib/libhello.so
sudo ldconfig
clean: uninstall
rm -f *.o *.so $(TARGETS)
test.sh:
#!/bin/sh
test1() {
echo test1: LD_LIBRARY_PATH
make -s test1
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
./test1
unset LD_LIBRARY_PATH
make -s clean
}
test2() {
echo test2: rpath
make -s test2
./test2
make -s clean
}
test3() {
make -s test3
echo test3: ld.so
./test3
make -s clean
}
test1
echo
test2
echo
test3
In the first test, we load the library by specifying the path to directory where
the library is. For that LD_LIBRARY_PATH
variable is used.
In the second test, we hardcode the path inside program test2
.
For the last test we need root privileges. We install the library to standard system
location and run ldconfig
to update ld.so
cache.