请教一个关于Dll的问题

Username_for_forum 2008-04-01 03:44:15
我做了一个MFC扩展的Dll。在Dll中定义了一个导出函数(add)和一个导出变量(total,初值是0)。其中在add中将total的值改成5.
在调用程序中先调用Dll的add函数然后输出total的值,每次都是0.为什么不是5呢?谁能帮我解释一下,谢谢。
主要代码如下:
--------
global.h

extern "C"
{
int AFX_EXT_DATA total = 0;
int AFX_EXT_API add(int x,int y);
};
--------
global.cpp

#include "StdAfx.h"
#include "global.h"
//extern "C" int total;
int add(int x, int y)
{
total = x + y;
return total;
}
---------
调用端:
#pragma comment(lib,"..\\Debug\\ExtMFCImportVarFunction.lib")
#include "global.h"

int main(int argc, char* argv[])
{
cout<<add(2,3)<<endl;
cout<< total<<endl;
return 0;
};
...全文
78 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Username_for_forum 2008-04-03
  • 打赏
  • 举报
回复
非常感谢二位的帮助。我已经知道如何改了。总结一下:
用Dll导出变量,如果希望Dll本身改变这个变量的值需要注意下面2点:
1.导出变量在哪个文件里定义就要在那个文件里修改:
比如在我的例子中,如果global.h 写成
--------
global.h

extern "C"
{
int AFX_EXT_DATA total;
int AFX_EXT_API add(int x,int y);
};
--------
说明在.h文件中定义了一个导出变量total。如果希望add函数改变total的输出值,则要把add函数的实现写在global.h中。

2.如果要在Dll的cpp文件中修改导出变量的值,则要在cpp文件中定义此变量,同时在.h中声明该变量为导入变量。
在我上面的例子中,可以把代码改成下面的样子:
---------
global.h

extern "C"
{
int _declspec(dllimport) total;
int AFX_EXT_API add(int x,int y);
};
---------
global.cpp
#include "StdAfx.h"
#include "gobal.h"

int total;
int add(int x,int y)
{
total = x + y;
return total;
}
---------
stellarguy 2008-04-01
  • 打赏
  • 举报
回复
写的不全:
global.h
--------
#ifdef YOURAPPLIBAPI


#else


#define YOURAPPLIBAPI extern "C" __declspec(dllimport)

#endif

YOURAPPLIBAPI int total = 0;
YOURAPPLIBAPI int add(int x,int y);


--------
global.cpp
#define YOURAPPLIBAPI extern "C" __declspec(dllexport)
....
ouyh12345 2008-04-01
  • 打赏
  • 举报
回复
global.h

extern "C"
{
int AFX_EXT_DATA total;
int AFX_EXT_API add(int x,int y);
};
--------
global.cpp

#include "StdAfx.h"
#include "global.h"

total = 0;

//extern "C" int total;
int add(int x, int y)
{
total = x + y;
return total;
}
stellarguy 2008-04-01
  • 打赏
  • 举报
回复
global.h
--------
#ifdef YOURAPPLIBAPI



#else


#define YOURAPPLIBAPI extern "C" __declspec(dllimport)

#endif

--------
global.cpp
#define YOURAPPLIBAPI extern "C" __declspec(dllexport)
....


15,466

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧