在dll和exe中使用全局变量 [英] using global variable in dll and exe

查看:354
本文介绍了在dll和exe中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在公共头文件中有一个全局变量。例如,

i have an global variable in an common header file. Eg

commonHeader.h

commonHeader.h

int commonInt = 0;

int commonInt = 0;

我有3个dll项目要在其中使用,因此我包含上面的标头,但是它给了我多次定义的错误符号,#pragma一次也行不通。

i have 3 dll projects in which i want to use it , so i include above header, but it give me error symbol defined multiple times , #pragma once also did't work.

如果我在变量extern中进行设置,并在我的exe中定义它,则我的dll中出现链接器错误。

if i make above variable extern , and define it in my exe i get linker errors in my dll.

我所有的dll都需要在标头上方。
我的一个dll需要其他2个dll的头文件(可能使syombol包含多个)

all my dll need above header. one of my dll need other 2 dll's header file (probably making multiple include of syombol)

我如何解决上述问题,我只希望跨一个变量dll和exe。

how i can resolve above issue , i want only one variable across dll and exe.

我在Windows 7上使用VS 2010 prof。

i am using VS 2010 prof on windows 7.

预先感谢。

推荐答案

通过在头文件中包含该全局变量定义,您违反了一个定义规则(第3.2节)。相反,只在带有 extern 的头文件中声明它,然后在单个实现文件中具有定义是正确的。

You're violating the One Definition Rule (§ 3.2) by having that global variable definition in a header file. Instead you were correct to only declare it in a header file with extern and then have the definition in a single implementation file.

但是为了使dll能够正常工作,您还必须将其声明为由exe导出并由dll通过 __ declspec(dllexport)和<$ c导入$ c> __ declspec(dllimport),使用适当的宏来选择正确的 __ declspec ,具体取决于您是编译exe还是dll。

But in order to have this work with dlls you also have to declare it as exported by the exe and imported by the dlls with __declspec(dllexport) and __declspec(dllimport), using appropriate macros to choose the right __declspec depending on whether you're compiling the exe or the dlls.

这篇关于在dll和exe中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆