静态库的编写

来源:互联网 发布:nginx cc攻击怎么防御 编辑:程序博客网 时间:2024/06/07 16:40

使用VC++2008


头文件

#ifndef READ_H#define READ_H#ifdef __cplusplus   //对于此处上完全明了,但去掉后有编译错误。extern "C" {  #endif    char *readText(char *fn);  #ifdef __cplusplus  }  #endif  #endif

实现文件

#include <stdio.h>#include <stdlib.h>#include "readtext.h"char *readText(char *fn){FILE *fp;char *content = NULL;int count=0;if (fn != NULL){fp = fopen(fn,"rt");if (fp != NULL){      fseek(fp, 0, SEEK_END);  // 重定位流(数据流/文件)上的文件内部位置指针                           // int fseek(FILE *stream, long offset, int fromwhere);      count = ftell(fp);       // long ftell(FILE *stream); 返回当前文件指针,是int类型      rewind(fp);  // void rewind(FILE *stream); 将文件内部的位置指针重新指向一个流(数据流/文件)的开头if (count > 0){content = (char *)malloc(sizeof(char) * (count+1));  // extern void *malloc(unsigned int num_bytes);count = fread(content,sizeof(char),count,fp);  // 从一个流中读数据                                                                  //函数原型: size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); content[count] = '\0';}fclose(fp);}}return content;}

编译成功后release文件夹中有lib文件即是静态库。


将lib文件放在当前目录下。

测试如下

#include <stdio.h>#include <stdlib.h>#include "readtext.h"#pragma  comment(lib,"../readtext.lib")  //此处为相对路径的写法int main(){    char *ff;ff=readText("../first.vert");  //此处也为相对路径printf("%s\n",ff);getchar();return 0;}

上图为测试结果。

1 0
原创粉丝点击