• dllexport和dllimport


    在VS中,如果要跨项目使用类或变量,就必须用到dllexport和dllimport,下面分别举例全局变量,函数和类跨项目使用。
    环境准备:使用VS分别新建一个windows应用程序和DLL项目,windows应用程序项目名称为ConsoleApplication1,DLL项目名称为testExtern。
    在这里插入图片描述
    在这里插入图片描述
    在ConsoleApplication1上右键项目属性
    在这里插入图片描述
    附加库目录加上testExtern生成dll和lib所在的目录
    在这里插入图片描述
    附加依赖项加上testExtern.lib名称

    全局变量

    在同一个项目中,全局变量不需要导出,extern声明一下即可:
    test.cpp中定义:

    int a = 100;
    
    • 1

    main.cpp中使用:

    extern int a;
    int main()
    {
    	cout << a << endl;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出100;

    在textExtern项目中定义全局变量(只有定义了导出宏时才会生成lib文件),则需要将其导出:

    int _declspec(dllexport) sssss = 1000000;
    
    • 1

    在ConsoleApplication1中使用sssss这个全局变量时,则需要导入:

    extern  int _declspec(dllimport)  sssss;
    int main() 
    {
    	cout << sssss << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    函数

    一定要在函数定义时声明导出:

    void _declspec(dllexport) myFun()
    {
    	std::cout << "myFun()" << std::endl;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在main.cpp中包含声明的头文件,不包含头文件则需要extern并声明导入

    int main() 
    {
    	myFun();
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在testExtern项目中ExportClass必须在定义时导出,在ConsoleApplication1中使用时必须包含其头文件

    class _declspec(dllexport) ExportClass
    {
    public:
    	void testExportClass();
    };
    void ExportClass::testExportClass()
    {
    	std::cout << "textExportClass()" << std::endl;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    main.cpp中:

    #include "C:\Users\Administrator\Documents\Visual Studio 2015\Projects\ConsoleApplication1\testExtern\extern.h"
    int main() 
    {
    	ExportClass ex;
    	ex.testExportClass();
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    秋招准备--基础知识复习--系统编程
    接口自动化中如何完成接口加密与解密?
    redux最佳实战(一)
    SpringBoot集成RocketMQ实现分布式事务
    黑*头条_第4章_文章搜索前后端成形记 & 实名认证审核
    你我他是谁
    [极客大挑战 2019]BuyFlag
    haproxy负载均衡
    性能测试你需要懂这些
    m3u8是什么?
  • 原文地址:https://blog.csdn.net/bureau123/article/details/125544923