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 -Wall2. Create shared library from the object file generated
gcc -shared -o libfun.so functions.o3. Compile the main program with shared library
gcc -o output main.c -lfun
/usr/bin/ld: cannot find -lfun
collect2: ld returned 1 exit status4. Compile with giving path of shared library
gcc -L/home/sujin/shared/ -Wall -o output main.c -lfun5. Run the program
./output
./output: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory6. Check current LD_LIBRARY_PATH.
echo $LD_LIBRARY_PATH7. If LD_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_PATH8. 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_PATH10. Run the program
./output
25353025
No comments:
Post a Comment