How to link dynamic and static libraries to the c program

How to link dynamic and static libraries to the c program


1. create directory libtest   [absolute path: /home/labuser/c_program_expts/libtest]

2. in "libtest" directory, 
create process2.c

filename: process2.c
code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

void neel1(void)
{
  printf("Hi.. i am the library");
}

3. create "Makefile" in libtest folder:
Neelkanth$ cat Makefile

CC := gcc
CFLAGS += -MMD -Wall -fomit-frame-pointer -fPIC -g
LDFLAGS += -shared

# includes
#CFLAGS += -I$(PCD_ROOT)/ipc/include

obj-y := $(patsubst %.c,%.o,$(shell ls *.c 2> /dev/null))
TARGET = libtest

all: $(TARGET) install

$(TARGET): $(obj-y)
        @echo "  LINK           $@"
        @$(AR) rcs $@.a $(obj-y)
        @$(CC) $(CFLAGS) $(obj-y) -o $@.so $(LDFLAGS) -Wl,-Map,$@.map

install: $(TARGET) install_internal

install_internal:
        @@mkdir -p lib
        @install $(TARGET).a lib
        @install $(TARGET).so lib

clean:
        @rm -f $(TARGET).so $(TARGET).a $(obj-y) $(obj-y:.o=.d) $(TARGET).map

%.o: %.c
        @echo "  CC [C]         $@"
        @$(CC) $(CFLAGS) -c $(CURDIR)/$< -o $@

-include $(obj-y:.o=.d)

4. run "make"
Neelkanth$ make
  CC [C]        process2.o
  LINK          libtest


5. create process1.c  [absolute path: /home/labuser/c_program_expts]

filename: process1.c
code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc == 0) {
        printf("\nenter atleast one argument\n");
    }
    else if (argc >= 3) {
        printf("\ncannot accept more than 1 argument\n");
    }
    else {
        neel1();
        printf("\n Argument: %s \n", argv[1]);
    }
    neel1(4, NULL);
    return 1;
}

6. compile process1.c
 gcc -c process1.c -o process1.o 

7.  
If you invoke the executable, the dynamic linker will not be able to find the required shared library. By default it won’t look into current working directory. You have to explicitly instruct the tool chain to provide proper paths. The dynamic linker searches standard paths available in the LD_LIBRARY_PATH and also searches in system cache (for details explore the command ldconfig). We have to add our working directory to the LD_LIBRARY_PATH environment variable. The following command does the same.

export LD_LIBRARY_PATH=libtest/lib:$LD_LIBRARY_PATH

8. 
 gcc -o final process1.o -Llibtest/lib -ltest

9. execute final
Neelkanth$ ./final

Hi.. i am the library
 Argument: (null)
Hi.. i am the library