Create shared library for C program in Linux

Consider you c program has two file, which are functions.c and main.c

Consider your current working directory is /home/sujin/shared/

functions.c
int add(int x, int y)
{
    return x + y;
}
 
int sub(int x, int y)
{
        return x - y;
}
 
int mul(int x, int y)
{
        return x * y;
}
 
int div(int x, int y)
{
        return x / y;
}
main.c
#include <stdio.h>
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
 
int main(int argc, char *argv[])
{
    printf("%d\n", add(10, 15));
        printf("%d\n", sub(50, 15));
        printf("%d\n", mul(10, 3));
        printf("%d\n", div(100, 4));
        return 0;
}

1. Compile library source file(functions.c) into position independent code
gcc -c -fpic functions.c -Wall
2. Create shared library from the object file generated
gcc -shared -o libfun.so functions.o 
3. Compile the main program with shared library
gcc -o output main.c -lfun
/usr/bin/ld: cannot find -lfun
collect2: ld returned 1 exit status
4. Compile with giving path of shared library
gcc -L/home/sujin/shared/ -Wall -o output main.c -lfun
5. Run the program
./output 
./output: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory
6. Check current LD_LIBRARY_PATH. 
echo $LD_LIBRARY_PATH
7. ILD_LIBRARY_PATH is not current working directory or empty then set the LD_LIBRARY_PATHS as current working directory
LD_LIBRARY_PATH=/home/sujin/shared:$LD_LIBRARY_PATH
8. Run the program
./output 
./output: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory
9. Export the LD_LIBRARY_PATH. In linux we need to export the changes in the environment variable
export LD_LIBRARY_PATH=/home/sujin/shared/:$LD_LIBRARY_PATH
10. Run the program
./output
25
35
30
25

No comments:

Post a Comment