linux compile a dynamic library

#include <stdio.h>   //num.c

int add_num(int a, int b){
	return a+b;
}

int sub_num(int a, int b){
	return a-b;
}
#include <stdio.h>   //print.c

int print_num(int n){
	printf("result is %d\n", n);
	return 0;
}
#include <stdio.h>   //hw.c
#include <my_lib.h>
int main(){
	int ret=0;
	int a=8,b=5;
	ret=add_num(a,b);
	print_num(ret);
	ret=sub_num(a,b);
	print_num(ret);
	return 0;
}
#ifndef __MY_LIB_H__
#define __MY_LIB_H__

int add_num(int a, int b);
int sub_num(int a, int b);

int print_num(int n);
#endif

 

The above is the four files and the compilation process. Then talk about the situation encountered by the compiler

The first step, compile a dynamic library gcc -o libnum.so -fPIC -shared num.c print.c 

1. -shared, we all know, ah, abbreviation share object when .so. In order to know at compile gcc .so instead of an executable file, so you need -shared

2. -fPIC, it is necessary to compile a dynamic library. Visible place the yellow circled, compiled separately, did not add -fPIC, the error will remind recompiled. In fact -fPIC compiler option, PIC Position Independent Code is an abbreviation, it said to generate position independent code, which is characteristic of dynamic libraries needed.

The second step, dynamic link libraries, the compiled executable file gcc -o test hw.c -I. -L. -Lnum, nothing to say

The third step is to run the resulting executable file.

We found a system error. Can not find libnum.so, original Linux is searching for dynamic libraries to be linked by /etc/ld.so.cache file. The program reads /etc/ld.so.cache ldconfig /etc/ld.so.conf file is generated.
(Note, /etc/ld.so.conf and does not have to contain  /lib and  /usr/lib, ldconfigthe program will automatically search both directories)

If we  libnum.so add the path to where  /etc/ld.so.conf , and then run with root privileges  ldconfig , updates  /etc/ld.so.cache , a.outrun-time, you can find  libmum.so.

But for this purpose to change the system of things, not the line.

So, I found a way down there are what, in fact, added to the LD_LIBRARY_PATH libnum.so ok, in other words, it is to add about the current path.

The easiest way nature is export LD_LIBRARY_PATH = LD_LIBRARY_PATH: $ pwd.

But this re-open when they would go out again, not as good as wrote ~ / .profile or ~ / .bashrc good. source ~ / .profile to ok

Published 10 original articles · won praise 0 · Views 155

Guess you like

Origin blog.csdn.net/tjw316248269/article/details/104433343