6.静态函数库设计

6.静态函数库设计

程序设计中,离不开函数的使用。Linux应用程序设计中需要外部函数。主要是由函数库和系统调用来提供。

两者区别:

系统调用的是在Linux内核里的,函数库是在用户空间的。

函数库分类:

    函数库按照链接方式可分为:静态链接库和动态链接库。

Linux应用程序使用的这些函数库主要存在于/lib目录和/usr/lib目录下,其中采用*.so.*方式命名的是动态函数库,而以*.a方式命名的是静态函数库。

/lib:

/usr/lib:

静态链接库的特点:

程序所用到的库函数代码在链接时全被copy到程序中。导致的问题:如果有多个进程在内存中同时运行,并且使用了相同的库函数,那就会有多份拷贝,这就是对空间的浪费。如下图:

编译选项:

  1. Linux下进行链接时默认是链接动态库
  2. 如果需要使用静态库,需要使用编译选项:-static

例子:gcc –static exm.c –o exm

下面看一个我们经常编译c文件的过程。在下面看到该程序用到*.so.*动态库。

生成的文件的大小:

加上-static参数后,编译出错:

这是因为redhat 6.4之后的版本不提供该功能了。我们需要安装该库:

glibc-static-2.12-1.80.el6.i686.rpm

ll看静态编译生成的文件比较大:

制作静态库:

使用自己制作静态库:

-lname:gcc在链接时,默认只会链接C函数库,而对于其他的函数库,则是需要使用-l选项来显示地指明需要链接的库:

例子:gcc hello.c –lmylib –o hello.

注意:静态链接库的命名:

    Libmylib.a:其中lib是必须加的,就是静态链接库的名字为libmylib.a在引用的时候是-lmylib。

    动态链接库的命名,跟静态一样只是后缀为.so。

实例:

/*************************************************************************

> File Name: mylib.c

> Author: FORFISH

> Mail: 18300070848@163.com

> Created Time: Fri 16 Jan 2015 07:44:10 AM EST

************************************************************************/

#include <stdio.h>

int tax(int salary, int insurance){

    int tax_salary = salary - insurance;

    int temp = tax_salary -3500;

    if(temp<0){

        printf("your salary is too low to hand on tax! ");

        return 0;

    }

    if(temp<=1500){

        return temp*0.03-0;

    }

    if((temp>1500)&&(temp<=4500)){

        return temp*0.1-105;

    }

    if((temp>4500)&&(temp<=9000)){

        return temp*0.2-555;

    }

    if((temp>9000)&&(temp<=35000)){

        return temp*0.25-1005;

    }

    if((temp>35000)&&(temp<=55000)){

        return temp*0.3-2755;

    }

    if((temp>55000)&&(temp<=80000)){

        return temp*0.35-5505;

    }

    else{

        return temp*0.45-13505;

    }

}

打包生成库:

把生成的库libmylib.a拷贝到/usr/lib目录:

编写应用程序使用我们创建的静态链接库:

首先是创建一个c文件mytest.c:

#include <stdio.h>

#include "tax.h"

void main(){

    int my_tax =0;

    my_tax = tax(9500,1200);

    printf("I have to tax %d",my_tax);

}

头文件tax.h的代码:

int tax(int salary, int insurance);

编译运行如下:

原文地址:https://www.cnblogs.com/FORFISH/p/5188606.html