1.编写一个C++动态库并编译
测试源代码头文件dong
#pragma once
#include
#include
#if defined(WIN32) || defined(WIN64)
# ifdef MY_DLL_API //
# define MY_DLL __declspec(dllexport)
# else
# define MY_DLL __declspec(dllimport)
# endif
#else
# define MY_DLL
#endif
#ifdef __cplusplus
extern "C"
#endif
class MyDll
{
public:
MY_DLL MyDll();
MY_DLL ~MyDll();
MY_DLL void Print(const std::string& srt);
};
#ifdef __cplusplus
extern "C"
#endif
动态库cpp文件代码
#include "OpenFile.h"
MY_DLL MyDll::MyDll()
{}
MY_DLL MyDll::~MyDll()
{}
MY_DLL void MyDll::Print(const std::string& str)
{
std::cout << "log is: " << str << std::endl;
}
2.在visual studio进行一些设置
1)在解决方案资源管理器右键你的项目名称 点击属性设置
2)常规中注意平台和版本,和自己需要用的版本库对其
3)将目标文件扩展名和配置类型都配置成.dll
4)在预处理器中设置动态库中的需要的宏,然后点击确定保存配置
5)点击运行编译此库
3.调用自己写的动态库
1)测试源代码
#include "OpenFile.h"
#include
int main()
{
MyDll test;
test.Print("hahaha");
system("pause");
return 0;
}
2)配置设置,同样的点击解决方案资源管理器右键你的项目名称 点击属性设置(和第2大点的第一小点一样)
3)在属性配置--->C/C++/---->常规--->附加包含路径目录中(是动态库头文件.h的目录)加上该路径
4)在链接器--->常规---->附加库目录加上刚才生成动态库的路径
5)在链接器---->附加依赖项中加上刚才生成静态库的路径,点击确定保存设置(注意编译版本匹配)
6)点击编译运行
7)复制刚才的动态库到生成的.exe路径
8) 运行结果