VS2017创建了静态库项目却一片空白

VS2017创建了静态库项目却一片空白,第1张

1.. 创建工程——win32项目 My_Static_lib_1

2.. 选择静态库,预编译头和安全开发生命周期(SDL)检查可要也可不要,我们这里选择不要

3.. 完成

4.. 添加源文件:static.cpp

测试程序

#include "static.h"

int sum(int m,int n)

{

return m + n

}12345

5..添加头文件static.h

测试程序

#ifndef STATIC_H

#define STATIC_H

int sum(int m, int n)

#endif1234

6.生成解决方案

之后你会在工程的Debug下发现生成了一个静态库

My_Static_lib.ib

至此,静态库已经生成

B:如何使用静态库

1.新建一个 win32项目 工程 Test_my_lib

2控制台应用程序(O)和空项目

3

把前面生成的静态库My_Static_lib_1.lib和static.h复制到此工程里,并把头文件添加到工程里

4

添加测试程序

#include<iostream>

#include "static.h"

using namespace std

#pragma comment(lib,"My_Static_lib_1.lib")

int main()

{

cout <<sum(2, 3)

getchar()

return 0

}

1234567891011

5运行,可以看到结果

1.静态链接库

打开VS2010,新建一个项目,选择win32项目,点击确定,选择静态库这个选项,预编译头文件可选可不选。

在这个空项目中,添加一个.h文件和一个.cpp文件。名字我们起为static.h和static.cpp

static.h文件:

[cpp] view plaincopy

#ifndef LIB_H

#define LIB_H

extern "C" int sum(int a,int b)

#endif

static.cpp文件:

[cpp] view plaincopy

#include "static.h"

int sum(int a,int b)

{

return a+b

}

编译这个项目之后,会在debug文件夹下生成static.lib文件,这个就是我们需要的静态链接库。

下面说明如何调用静态链接库。

首先需要新建一个空项目,起名为test。将之前static项目下的static.h和static.lib这个2个文件复制到test项目的目录下,并在工程中加入static.h文件。

新建一个test.cpp文件如下:

[cpp] view plaincopy

#include <stdio.h>

#include <stdlib.h>

#include "static.h"

#pragma comment(lib,"static.lib")

int main()

{

printf("%d\n",sum(1,2))

system("pause")

return 0

}

编译运行可得结果:3

#pragma comment(lib,"static.lib"),这一句是显式的导入静态链接库。除此之外,还有其他的方法,比如通过设置路径等等,这里不做介绍。

2.动态链接库

和创建静态链接库一样,需要创建一个空的win32项目,选择dll选项。创建dynamic.cpp和dynamic.h文件

dynamic.h文件:

[cpp] view plaincopy

#ifndef DYNAMIC

#define DYNAMIC

extern "C" __declspec(dllexport)int sum(int a, int b)

#endif DYNAMIC

dynamic.cpp文件:

[cpp] view plaincopy

#include "dynamic.h"

int sum(int a, int b)

{

return a+b

}

编译这个项目,会在debug文件夹下生成dynamic.dll文件。

下面介绍如何调用动态链接库,这里讲的是显式的调用。

在刚才的test项目下,把static.lib和static.h文件删除,把dynamic.h和dynamic.dll复制到该目录下,并在项目中添加dynamic.h文件,修改test.cpp文件为:

[cpp] view plaincopy

#include <stdio.h>

#include <stdlib.h>

#include<Windows.h>

#include "dynamic.h"

int main()

{

HINSTANCE hDll=NULL

typedef int(*PSUM)(int a,int b)

PSUM pSum

hDll = LoadLibrary(L"dynamic.dll")

pSum = (PSUM)GetProcAddress(hDll,"sum")

printf("%d\n",pSum(1,2))

system("pause")

FreeLibrary(hDll)

return 0

}

编译运行结果为:3

特别提示:

1.extern "C"中的C是大写,不是小写

2.如果从VS2010中直接运行程序,lib和dll需要放到test项目的目录下;如果想双击项目test下的debug文件中的exe文件直接运行的话,需把lib和dll放入debug文件夹下。

项目属性-配置属性-常规-MFC的使用-使用标准Windows库(不用MFC)然后,C/C++-代码生成-运行库-多线程/MT或者多线程调试/MTd带d的是链接调试版本,DEBUG项目选/MTd,Release项目选/MT如果使用MFC,在MFC的使用中设置静态、动态链接,代码生成


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11795750.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存