Create a dynamic link library under visual studio2019

Open visual studio2019 create a dynamic link library project, the project name for the 20199324dll

Then define the macro: can be defined in the header file, the effect is to allow the macro function can be externally accessible, and direct calls. code show as below:

// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。

#ifndef PCH_H
#define PCH_H

// 添加要在此处预编译的标头
#include "framework.h"

#endif //PCH_H


//定义宏

#ifdef IMPORT_DLL

#else
#define IMPORT_DLL extern "C" _declspec(dllimport) //指的是允许将其给外部调用
#endif

IMPORT_DLL int add(int a, int b);
IMPORT_DLL int minus(int a, int b);
IMPORT_DLL int multiply(int a, int b);
IMPORT_DLL double divide(int a, int b);

These can then implement in pch.cpp file, as follows:

// pch.cpp: 与预编译标头对应的源文件

#include "pch.h"

// 当使用预编译的头时,需要使用此源文件,编译才能成功。

int add(int a, int b)
{
    return a + b;
}

int minus(int a, int b)
{
    return a - b;
}

int multiply(int a, int b)
{
    return a * b;
}

double divide(int a, int b)
{
    double m = (double)a / b;
    return m;
}

Next is click generation, will generate 20199324dll.dll files in the debug directory (this is what we needed)

Then create a console application to test whether a successful call dll, named 20199324dlltest

The introduction of windows.h (must) ; write the following statement in the main function call dll, code is as follows:

// 20199324dlltest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。

#include <iostream>
#include<windows.h>

int main()
{
    HINSTANCE hDllInst;
    hDllInst = LoadLibrary(L"20199324dll.dll"); //调用 DLL    
    typedef int(*PLUSFUNC)(int a, int b); //后边为参数,前面为返回值    
    PLUSFUNC plus_str = (PLUSFUNC)GetProcAddress(hDllInst, "add");//GetProcAddress为获取该函数的地址 
    std::cout << plus_str(93,24);
}

Note : the need to previously generated dll file, copied to the debug console program directory!

Click Local Windows Debugger:

Reference: https://blog.csdn.net/Giser_D/article/details/89677441

Guess you like

Origin www.cnblogs.com/yangdd/p/11876608.html