C .so Dynamic libs ldconfig ldd

Posted on July 1, 2014
Tags: c

The equivalent of windows .dll are linux .so files. In linux static libraries are .a files.

Dynamic linked library can be stored in your OS /usr/lib.
C binaries built by default dynamically links glibc library

#ifndef __DEMO_H__
#define __DEMO_H__

char* DEMOreverse(char *string);

#endif 
#include "DEMO.h"
#include <string.h>

char* DEMOreverse(char* string){
    int len= strlen(string);
    for(int i = 0; i < len/2; i++){
        char temp = string[i];
        string[i] = string[len-1-i];
        string[len-1-i] =temp; 
    }
    return string;

}
#include "DEMO.h"
#include <stdio.h>

int main(int argc, char **argv){
    printf("%s\n",argv[1]);
    printf("%s\n",DEMOreverse(argv[1]));
}
CC=gcc
CFLAGS=-Wall -g
BINS=DEMObinary DynLinkedBinary
all: $(BINS)

libDEMO.o: libDEMO.c DEMO.h
	$(CC) $(CFLAGS) -c libDEMO.c
DEMObinary: main.c libDEMO.o
	$(CC) $(CFLAGS) -o $@ $^

# building the dynamic linked library
libDEMO.so: libDEMO.c DEMO.h
	$(CC) $(CFLAGS) -fPIC -shared -o $@	libDEMO.c -lc
# building the binary that uses the dynamically linked library
DynLinkedBinary: main.c libDEMO.o
	$(CC) $(CFLAGS) -o $@ $^ -L. -lDEMO

clean:
	rm *.o *.so $(BINS)

0.1 Analyze the commands

ldd DynLinkedBinary
# linux-vdso.so.1 (0x00007fff259f2000)
# libDEMO.so => not found
# libc.so.6 => /lib64/libc.so.6 (0x00007fe67d347000)
# /lib64/ld-linux-x86-64.so.2 (0x00007fe67d55c000)

libc.so.6 is glibc which is linked to all C programs built.
Notice libDEMO.so isnt detected even though it is in the same directory.

1 Where to put libDEMO.so?

sudo ldconfig -v -N
# ldconfig: Can't stat /libx32: No such file or directory
# ldconfig: Path `/usr/lib' given more than once
# (from <builtin>:0 and <builtin>:0)
# ldconfig: Path `/usr/lib64' given more than once
# (from <builtin>:0 and <builtin>:0)
# ldconfig: Can't stat /usr/libx32: No such file or directory
# /lib: (from <builtin>:0)
# /lib64: (from <builtin>:0)

from the above we see it checks the following directories for *.so files:
/libx32 /usr/lib /usr/lib64/ /usr/libx32 /lib /lib64

1.1 Solution

cp libDEMO.so /usr/lib/
#sometimes your OS will auto copy it to /lib as well

refresh the ldconfig cache (because maybe you threw the file in a bad destination and tried to update the ldconfig which cached the bad destination)

sudo ldconfig    
#clears cache and sync library
ldconfig -n -v /usr/lib/
# .: (from <cmdline>:0)
#         libDEMO.so -> libDEMO.so

Check if library is actually installed

ldconfig -p | grep libDEMO

Run the program

./DynLinkedBinary hello
# hello
# olleh

2 Extra

Sometimes you may see libSTUFF.so.1 libSTUFF.so.2
This just means libaries that get updated so they symlinked to the next number.

ln -s libname.so.1 libname.so
ln -s libname.so.2 libname.so.1
libSTUFF.so --> libSTUFF.so.1
libSTUFF.so.1 --> libSTUFF.so.2