静态链接库的编写

自己有时候写程序,写了就丢了,根本没有什么代码的重用。看着那代码,每次都要重写,伤不起。

最近看了下静态链接库和动态链接库的编写方法,个人还是比较喜欢静态链接库,虽然程序会更大,但如果不小心弄掉了DLL文件,就什么都不能用了。

 

首先,创建一个静态链接库工程,名称为ConvertStaticLib

这个静态链接库有一个函数,把二进制数转换为十进制数

首先在StdAfx.h中添加

1 #include <windows.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 
5 
6 extern "C" void Convert(char* szDecOutput,char* szBinInput);

其中头文件是编写函数过程中用的头文件

extern "C" void Convert(char* szDecOutput,char* szBinInput);相当于导出函数

 

下面是真正的实现部分

 1 // stdafx.cpp : source file that includes just the standard includes
 2 //    ConvertStaticLib.pch will be the pre-compiled header
 3 //    stdafx.obj will contain the pre-compiled type information
 4 
 5 #include "stdafx.h"
 6 
 7 //将二进制转换为十进制
 8 void Convert(char* szDecOutput,char* szBinInput)
 9 {
10     int nDecimal=0;
11     int Len=lstrlen(szBinInput);
12     for (int i=0;i<Len;i++)
13     {
14         char h = szBinInput[Len-1-i];                                    
15         char str[1];
16         str[0]=h;
17         int j = atoi(str);                                              
18         for (int k=0;k<i;k++)                                            
19         {
20             j = j*2;
21         }
22         nDecimal = nDecimal+j;    
23     }
24     sprintf(szDecOutput,"%d",nDecimal);
25 }

这样,静态链接库就写好了,编译一下。

=====================================================================

创建一个新的工程,为一个控制台程序

将静态链接库编译后的文件放入到该工程目录下

在实现文件中添加

1 #pragma comment(lib,"ConvertStaticLib.lib")
2 
3 extern "C" void Convert(char* szDecOutput,char* szBinInput);

这样,就可以在代码中使用该函数了。

下面是一个简单的例子

 1 #include "stdafx.h"
 2 #include <stdio.h>
 3 
 4 #pragma comment(lib,"ConvertStaticLib.lib")
 5 
 6 extern "C" void Convert(char* szDecOutput,char* szBinInput);
 7 
 8 
 9 int main(int argc, char* argv[])
10 {
11     char tk[256]="";
12     char Input[]="10101010101001";
13     Convert(tk,Input);
14     printf("%s\n",tk);
15     printf("hello\n");
16     return 0;
17 }

其实就是将input作为输入,将tk作为输出,通过Convert转换,将二进制转换为对应的十进制。

结果为

我们先用计算器验证一下,发现结果是正确的,至于可能有其它的问题,需要在实际运用中发现,这里只是一个静态链接库的编写和运用。

如果有什么问题,欢迎你指出来。

posted @ 2012-06-30 10:26  r3call  阅读(503)  评论(0编辑  收藏  举报