工作几年了,才换到liunx确实不太习惯,但是对于程序猿来说,这未尝不是让人兴奋的事情,能学到新的知识,每天都在进步。时间过的也确实快。。。。
那现在开始编写第一个静态引用库:
一般步骤:
1.编写cpp文件
2:编译成.o文件,注意用gcc -c,一定要加-c不然会生成可执行文件
3:ar 命令生成静态库
4:引用静态库
编写头文件:001_test.hpp
/*
* 001_test.hpp
*
* Created on: 2015年11月24日
* Author: liug
*/
#ifndef _001_TEST_HPP_
#define _001_TEST_HPP_
#include "stdio.h"
#include "stdlib.h"
class testLib001
{
public:
testLib001();
~testLib001();
int GetSum(int iFirst,int iSecond);
private:
int m_iIndex;
};
#endif /* 001_TEST_HPP_ */
编写001_test.cpp
#include "001_test.hpp"
testLib001::testLib001():m_iIndex(0)
{
};
testLib001::~testLib001()
{
};
int testLib001::GetSum(int iFirst,int iSecond)
{
return iFirst + iSecond;
}
编译成静态库:
[root@localhost libtest]# gcc -c 001_test.cpp
会生成001_test.o
[root@localhost libtest]# ar -crv lib001_test.a 001_test.o
-c表示创建库
-r表示插入成员类或函数
-v表示更新版本
可以用命令:man ar查看
生成lib001_test.a静态库
最后使用静态库:
编写main.cpp
#include "001_test.hpp"
int main(int argc, char* *argv)
{
testLib001 t001Lib;
int iFirst = 10;
int iSecond = 20;
printf("Sum = %d\n",t001Lib.GetSum(iFirst,iSecond));
return 0;
}
链接编译可执行文件001_test
[root@localhost libtest]# g++ -L/data/XXXX/XXXX/test/libtest -g3 -Wall main.cpp -o 001_test.dbg lib001_test.a
-L指定静态库路径
-g3生成可调试文件,可以用gdb调试
-Wall编译打印所有警告信息
还有药用g++编译,要是用gcc编译可能报错,以下是错误信息,可能是gcc不支持
[root@localhost libtest]# gcc -L/data/qmonster/liugao/test/libtest -g3 -Wall main.cpp -o 001_test lib001_test.a
/tmp/cc4QhyKL.o:(.eh_frame+0x13): undefined reference to `__gxx_personality_v0'
lib001_test.a(001_test.o):(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
执行结果:
[root@localhost libtest]# ./001_test
Sum = 30
希望给新手有些帮助,也给自己留下笔记查看。。。
参看文章:http://www.cnblogs.com/skynet/p/3372855.html