Writing and invoking dynamic libraries under Linux
Writing and invoking a simple dynamic library under Linux is roughly divided into the following steps:
-Create a dynamic library program file
Add.c
int add(int a,int b){ return a+b;}
- To create a reference header file
Head.c
#ifndef _HEAD_#define _HEAD_int add(int a,int b);#endif
- To generate a target file
Build to add compiler option -fpic
gcc -fpic -c add.c
- Then generate the dynamic library
Note Use the linker option -shared
gcc -shared –o libhead.so add.o
- Write the main program to make the call
Main.c
#include <stdio.h>#include "head.h"int main(void){ printf("3+5 sum = %d \n",add(3,5)); return0;}
- Build executables and link library files
When compiling a program, using a dynamic-link library and a static library is consistent, using the "-L library name" approach.
-o main main.-L ./ -lhead
-l Specifies the path of the dynamic link library,-ldxx the link library function xx. -LXX is a call rule for dynamic libraries. The dynamic library naming method under the Linux system is lib*.so, while the link indicates that bit-l*,* is the name of the library itself.
whileshared libraries: libhead.so: opensharedfilefileor directory
This is because the program does not find the reason for the dynamic link library when it runs, and note that Linux does not automatically look for dynamic library files in the current directory. the solution generally has three kinds of, learn from the blog Garden Smartvessel Original:
- Use ln to link the required so file to the/usr/lib or/lib the two default directories below
-s /home/用户名/code/lib/*.so /usr/libsudo ldconfig
Note Fill in the path of the directory where your dynamic library is located, if you do not know the full path can be viewed with pwd . If the path is not correct, an error may occur:
sharedobjectError40
2. Modify Ld_library_path
export LD_LIBRARY_PATH=/home/用户名/code/lib/:$LD_LIBRARY_PATHsudo ldconfig
3. Modify the/etc/ld.so.conf and then refresh
vim /etc/ld.so.confadd /home/用户名/code/lib/sudo ldconfig
You must remember to update sudo ldconfig, or you will get an error.
./main3+5 sum = 8
OK, the test is successful, there are questions can be left message discussion!
Copyright NOTICE: This article for Bo Master applebite original article, reproduced please indicate the source.
Writing and invoking dynamic libraries under Linux