版权声明:转载请说明Zhonglihao原创 https://blog.csdn.net/xeonmm1/article/details/83627354
为了避免出现问题,请统一使用Visual Studio 2017
1.DLL生成
创建一个DLL库项目,在属性页中勾选生成DLL(配置类型)
在输出的选择中选择Release输出
主要函数和头文件如下:
// DllDemo.cpp : Defines the exported functions for the DLL application.
//
#define DllDemoAPI _declspec(dllexport)
#include "stdafx.h"
#include "DLLDEMO.h"
#include <stdio.h>
DllDemoAPI int my_add(int a, int b)
{
return a + b;
}
DllDemoAPI int my_subtract(int a, int b)
{
return a - b;
}
DllDemoAPI int my_multiple(int a, int b)
{
return a * b;
}
DllDemoAPI void Point::Print(int x, int y)
{
printf("x=%d,y=%d", x, y);
}
DLLDEMO.h
#include <iostream>
#define DLLProvider 1
#ifdef DLLProvider
#define DllDemoAPI _declspec(dllexport)
#else
#define DllDemoAPI _declspec(dllimport)
#endif
DllDemoAPI int my_add(int a, int b);
DllDemoAPI int my_subtract(int a, int b);
DllDemoAPI int my_multiple(int a, int b);
class DllDemoAPI Point
{
public:
void Print(int x, int y);
};
#pragma once
上面代码中声明DLLProvider则编译时使用输出模式,在输入中只要把DLLProvider声明去掉就可以了。
编译生成的文件如下
2.DLL调用
新建一个控制台应用,目录下新建一个目录放刚才生成的DLL文件:
DLLLIB目录放刚才生成的文件,工程目录下也放一次,这样就没啥问题了
新建一个DLLDEMO.h头文件,如下:
#include <iostream>
#ifdef DLLProvider
#define DllDemoAPI _declspec(dllexport)
#else
#define DllDemoAPI _declspec(dllimport)
#endif
DllDemoAPI int my_add(int a, int b);
DllDemoAPI int my_subtract(int a, int b);
DllDemoAPI int my_multiple(int a, int b);
class DllDemoAPI Point
{
public:
void Print(int x, int y);
};
#pragma once
在这里没有定义DLLProvider,所以会是使用dllimport的状态,这个是关键之一。
main页代码:
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
// DLLUSE.cpp : 定义控制台应用程序的入口点。
//
#include "DLLDEMO.h"
int main()
{
printf("5+3=%d\n", my_add(5, 3));
std::cout << "Hello World!\n";
}
在工程属性页中添加附加库目录,刚才的DLLLIB目录
在常规->附加包含目录中添加DLL的目录
输入->附加依赖项中添加.lib文件
成功跑起来,跑不起来的话开启微软符号服务器下载就可以了