C语言_静态编译和动态编译

编译静态库,在Mac系统下:

//
// hello1.h
//

#include "hello1.h"

void myPrint1(int i)
{
    int j;
    for(j = 0; j < i; j ++)
    {
        printf("%d * %d = %d\n", j, j, j * j);
    }
}
//
// hello1.c
//

#ifndef HELLO1_H_INCLUDED
#define HELLO1_H_INCLUDED

#include <stdio.h>

void myPrint1(int i);

#endif // HELLO1_H_INCLUDED
//
// hello2.h
//

#ifndef HELLO2_H_INCLUDED
#define HELLO2_H_INCLUDED

#include <stdio.h>

void myPrint2(char *arr);

#endif // HELLO2_H_INCLUDED
//
// hello2.c
//

#include "hello2.h"

void myPrint2(char *arr)
{
    char c;
    int i = 0;
    while((c = arr[i++])!= '\0')
    {
        printf("%d****%c\n", i, c);
    }
}
//
// main.c
//

#include <stdio.h>
#include <stdlib.h>
#include "hello1.h"
#include "hello2.h"

int main()
{
    int i = 100;
    char *arr = "This is Kity's home";

    myPrint1(i);
    myPrint2(arr);

    return 0;
}

可以看到main.c要用到hello1.c中的myPrint1函数和hello2.c中的myPrint2函数。所以可以把这两个函数组合为库,以供更多的程序作为组件来调用。

方法一:将hello1.c和hello2.c编译成静态链接库.a

// 将hello1.c和hello2.c分别编译为hello1.o和hello2.o,其中-c选项意为只编译不链接。
[root@localhost main5]#gcc -c hello1.c hello2.c   

//将hello1.o和hello2.o组合为libhello.a这个静态链接库
[root@localhost main5]#ar -r libhello.a hello1.o hello2.o   

//将hello.c编译为可执行程序hello.exe
[root@localhost main5]#gcc -o hello hello.c -libhello.a  

方法二:将hello1.o和hello2.o组合成动态链接库.so

 // 将hello1.c和hello2.c编译成hello1.o和hello2.o,-c意为只编译不链接,-fpic意为位置独立代码,指示编译程序生成的代码要适合共享库的内容这样的代码能够根据载入内存的位置计算内部地址。
[root@localhost main5]#gcc -c -fpic hello1.c hello2.c   

 // 将hello1.o和hello2.o组合为shared object,即动态链接库
[root@localhost main5]#gcc -shared hello1.o hello2.o -o hello.so 

//将main.c编译链接为hello.exe的可执行程序,这个过程用到了动态链接库hello.so
[root@localhost main5]#gcc -o hello hello.c hello.so  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值