菠萝的工程师养成日记

导航

一个含链接到库的C程序的编译过程 gcc+vim makefile

一、先用vim准备好几个源程序

1、库函数的头文件

dyhello1.h
#ifndef DYHL_H1
#define DYHL_H1
    int dyfunc1();
#endif
 
dyhello2.h
#ifndef DYHL_H2
#define DYHL_H2
    int dyfunc2();
#endif
 
sthello1.h
#ifndef STHL_H1
#define STHL_H1
    int stfunc1();
#endif
 
sthello2.h
#ifndef STHL_H2
#define STHL_H2
    int stfunc2();
#endif

2、库函数的C文件

dyhello1.c
#include <stdio.h>
int dyfunc1()
{
    printf("This is dyhello1 ,dyfunc1\n");
    return 0 ;
}
 
dyhello2.c
#include <stdio.h>
int dyfunc2()
{
    printf("This is dyhello2 ,dyfunc2\n");
    return 0 ;
}
 
sthello1.c
#include <stdio.h>
int stfunc1()
{
    printf("This is sthello1 , stfunc1\n");
    return 0 ;
}
 
sthello2.c
#include <stdio.h>
int stfunc2()
{
    printf("This is sthello2 , stfunc2\n");
    return 0 ;
}

3、主程序的C文件

#include <stdio.h>
#include "dyhello1.h"
#include "dyhello2.h"
#include "sthello1.h"
#include "sthello2.h"
int main()
{
    dyfunc1();
    dyfunc2();
    stfunc1();
    stfunc2();
    return 0 ;
}
 

二、生成库

1、静态库

gcc -c sthello*.c //编译静态库C文件
ar -rcs libsthello.a *.o//打包成一个静态库

2、动态库

gcc -shared -fpic dyhello*.c -o libdyhello.so//直接生成动态库

三、链接库

1、C文件编译时将C文件和库链接起来
gcc -o hello hello.c -L. -ldyhello -lsthello//  -o将hello.c编译成可执行文件hello;
                                                                    -L将库的地址告诉编译器 ;
                                                                    -l将库的名称告诉编译器 ;
2、C文件执行时将C文件和动态库链接起来
1)将动态库的地址直接加入到系统的动态库中
cp libdyhello.so /usr/lib
cp libdyhello.so /lib
2)将动态库地址添加为共享目录
export LD_LIBRARY_PATH=`pwd`
 

四、执行C文件

./hello
 
***************************************************************************************

makefile

用vim编写makefile文件
all: static_lib dynamic_lib  //以来static_lib dynamic_lib 两个命令的执行
        @gcc -o hello hello.c -L. -ldyhello -lsthello
        @export LD_LIBRARY_PATH=/home/tonghuijuan/2nd/ && ./hello         //注意此行  makefile里面每一个命令都是一个单独的进程  所以此处要用&&符号连接起两条命令
                                   上一条修改的LD_LIBRARY_PATH在下一条命令中才可生效
clean:
        @rm -rf *.o
static_lib:sthello*.c
        @gcc -c sthello*.c
        @ar -rcs libsthello.a *.o
        @rm -rf *.o
dynamic_lib:dyhello*.c
        @gcc -shared -fpic dyhello*.c -o libdyhello.so
 
 
@表示不显示本条命令
命令make  执行all目标
       make static_lib 执行static_lib目标

posted on 2018-01-22 14:32  菠萝的工程师养成日记  阅读(93)  评论(0)    收藏  举报