linux c以及vs静态链接库的编写及使用

来源:互联网 发布:中国互联网主干网络 编辑:程序博客网 时间:2024/06/18 01:47



 linux c 的静态库使用。

1.首先,我使用的IDE为netbeans。采用samba来共享windows与linux文件。

2.编写pr1.c

void print1(){    printf("pr1 ... \n");}

3.编写pr2.c

void print2(){    printf("pr2 ... \n");}

分析,2与3.并无预编译命令以及自定义头文件

4.编写一个头文件以及实现

lib_static.h

/*  * File:   lib_static.h * Author: Vicky * * Created on 2011年10月19日, 下午5:37 */#ifndef LIB_STATIC_H#defineLIB_STATIC_H#ifdef__cplusplusextern "C" {#endif    int add(int x,int y);#ifdef__cplusplus}#endif#endif/* LIB_STATIC_H */

lib_static.c

/*  * File:   lib_static.c * Author: Vicky * * Created on 2011年10月19日, 下午5:37 */#include "lib_static.h"int add(int x,int y) {    return x + y;}

5.编译并生存静态库文件:

cc -O -c pr1.c pr2.c lib_static.c

ls -l *.o   // 查看生成的pr1.o pr2.o 以及lib_static.o

ar -rsv lib_static.a pr1.o pr2.o lib_static.o    生成的静态连接规则为:lib[名称].a 使用时不用lib而只用[名称]

ls -l *.a  // 查看生存的.a静态库
ar -t lib_static.a  // 查看静态库

pr1.o
pr2.o
lib_static.o

6.编写主函数,调用静态库函数,这里将演示包含头文件以及不包含头文件的函数使用

/*  * File:   main.c * Author: Vicky.H * * Created on 2011年9月19日, 下午1:23 * 目的:测试静态链接库 */#include <stdio.h>#include <stdlib.h>#include "lib_static.h"/* *  */int main(void) {    print1();    print2();        int i = add(3,4);    printf("3 + 4 = %d",i);    return (EXIT_SUCCESS);}


7.
-L 加载库文件路径 -l 指定库文件名称

cc -o main main.c -L./ -l_static   注意不需要加空格,_static使用pr即可!

./main
    >>pr1 ...
    >>pr2 ...
    >>3 + 4 = 7

 

 

-------------------------------------------------------------------------------------------------------------------

 

vc编写静态链接库

1.创建头文件VLog1_0.h

int add(int x,int y);


2.创建VLog1_0.cpp

#include "stdafx.h"#include "VLog1_0.h"int add(int x,int y){return x + y;}


3.右键项目,"生成".将会生成一个名为"lib_static.lib"的文件

4.编写测试文件

// lib_static_test.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "VLog1_0.h"#include <iostream>#pragma comment(lib,"..\\Debug\\lib_static.lib")using namespace std;int _tmain(int argc, _TCHAR* argv[]){int sum = add(3,4);cout << "sum = " << sum << endl;getchar();return 0;}


5.运行 sum = 7