c++动态链接库及静态链接库的生成与使用

1,新建控制台工程xdltest,改属性-配置属性-常规-配置类型为 动态库.dll或静态库.lib
2,打开工程后添加 dltest.h, dltest.cpp,其中.h与.cpp名字没必要一样
3,编写代码
----------------------------------------------
--dltest.h
#pragma once
_declspec(dllexport) void Print(const char* str);

----------------------------------------------
--dltest.cpp
#include<iostream>
#include"dltest.h"
void Print(const char* str)
{
std::cout << "dltest>> " << str << std::endl;
}

4,编译,生成 <库的名字是根据工程名生成的>
若是静态库,则会生成 xdltest.lib.
若是动态链接库则生成 xdltest.lib 和 xdltest.dll

5,使用
(1)将xdltest.lib添加到 <属性-配置属性-链接器-输入-附加依赖项>
(2)在<属性-配置属性-链接器-常规-附加库目录>中指定xdltest.lib的目录
(3)在<属性-配置属性-c/c++-常规-附加包含目录>中指定dltest.h的目录
(4)在程序中 #include "dltest.h" 后即可使用Print("hello")输出了

下面有三种方式使用库函数
-----------------------------------------
--使用方式一
#include "stdafx.h"
#include "abc.h" //包含库的头文件

int main()
{
Print("hello,world");
return 0;
}
-----------------------------------------
--使用方式二
#include "stdafx.h"
void Print(const char* str); //声明库中的函数,使编译通过

int main()
{
Print("hello,world");
return 0;
}
-----------------------------------------
--使用方式三
#include "stdafx.h"
_declspec(dllimport) void Print(const char* str); //从库中导入进工程

int main()
{
Print("hello,world");
return 0;
}
6,运行
若是动态链接库则必须把dll文件拷到exe目录下才能运行

原理:
.h文件用于编译,使程序在语法上检测通过,利用这个原理,
可以不使用.h文件而直接将需要使用的库函数在使用前声明出来
.lib文件用于链接,若是静态链接库,直接将函数实现写入了exe中,
若是动态链接则是在exe中留下函数签名并标记它是运行时动态加载的

------------------------------------------------------------------------------------------------------

需要注意的是:

1,C#只能调用 C/C++的DLL,而不能调用lib,

2,C++生成的DLL中,函数名被改了(各编译器而不同),而C#调用C++ DLL时需要指定函数名字,因此会出错,找不到函数

对应方法是:生成C风格的DLL,它的函数是没改名字的。

C风格的DLL中函数声明加上 exterun "C",如:

 exterun "C" _declspec(dllexport) void Print(const char* str);

猜你喜欢

转载自www.cnblogs.com/timeObjserver/p/9379202.html
今日推荐