在windows平台使用Visual Studio 2017编译动态库并使用

小董同学、 / 2023-07-24 / 原文

使用VS stdio制作顺序表的库文件

  • .lib与.dll 区别
    • lib是编译时需要的
    • dll是运行时需要的

1、新建头文件和源文件

  • SeqList.h
// SeqList.h
#ifndef SEQLIST_H__
#define SEQLIST_H__

#define N 10

typedef int SLDataType;

typedef struct SeqList
{
	SLDataType data[N];
	int size;
} SeqList;

void SeqInit(SeqList *L);                   // 初始化
void SeqPushBack(SeqList *L, SLDataType x); // 尾插
void SeqPrit(SeqList ps);                   // 打印

#endif
  • SeqList.c
// SeqList.h
#include <stdio.h>
#include <stdlib.h>

#include "SeqList.h"

void SeqInit(SeqList *L)
{
	L->size = 0;
}

void SeqPushBack(SeqList *L, SLDataType x)
{
	L->data[L->size] = x;
	L->size++;
}

void SeqPrit(const SeqList L)
{
	for (size_t i = 0; i < L.size; i++)
	{
		printf("%d\t", L.data[i]);
	}
	printf("\n");
}

2、编译.lib库文件

依次点击调试-属性,打开属性页面。

image

属性页面,选择配置Debug,平台选择x64,更改常规-属性默认值-配置类型选项,并选择 静态库

image

点击生成-生成解决方案,看到生成SeqList.lib

x64-Debug文件下面可以看到生成的SeqList.lib

image

2、编译.dll库文件

然后再点击生成-清理生成解决方案,并同样打开属性页面。

image

更改常规-属性默认值-配置类型选项,并选择动态库

image

点击生成-生成解决方案,看到生成SeqList.dll

image

x64-Debug文件下面可以看到生成的 SeqList.dll

image

至此,SeqList.libSeqList.dll都已经制作成功,下面开始使用。

使用SeqList.libSeqList.dll

新建解决方案Project.sln,并新建includelib文件,并将SeqList.hSeqList.dll复制到.sln 同级目录。

image

依次点击调试-属性,打开属性配置页面。将includelib目录分别加到包含目录库目录

image

并在连接器-添加附加依赖项中加入SeqList.lib

image

然后编写测试文件,注意此时没有用到SeqList.c

#include <stdio.h>
#include <stdlib.h>

#include "include/SeqList.h"

int main(int argc, char** argv)
{
	SeqList L;
	SeqInit(&L);
	SeqPushBack(&L, 1);
	SeqPushBack(&L, 5);
	SeqPushBack(&L, 9);
	SeqPushBack(&L, 7);
	SeqPrint(L);

	return 0;
}

点击生成解决方案,运行结果如下

image

行文至此,关于自定义库文件的制作与使用全部介绍完毕。