0

我必须从我的 .cpp 和 .h 文件创建一个静态链接的独立 .exe 文件。

我需要克服的唯一障碍是能够m_pListAll()从两个 .cpp 文件中调用相同的函数,main.cpp并且window.cpp(定义一个名为 的类Window)。

唯一的问题是(由于未知原因)我不能#include定义 m_peDO() 两次的头文件main.cppwindow.cpp我只能做一次,因为头文件设置了一个叫做“动态链接”的东西,有一些奇怪的东西叫做HINSTANCE(错误:实际原因在答案部分):

            //linking.h

            //  This is an extra header file for dynamic linking of the LabJackUD driver.
            //  support@labjack.com

            #ifdef  __cplusplus
            extern "C"
            {
            #endif 

            //For dynamic linking, we first define structures that have the same format
            //as the desired function prototype.
            typedef LJ_ERROR (CALLBACK *tListAll) (long, long, long *, long *, long *, double *);


            //Define a variable to hold a handle to the loaded DLL.
            HINSTANCE hDLLInstance;

            //Define variables for the UD functions.
            tListAll m_pListAll;

            #ifdef  __cplusplus
            } // extern C
            #endif

还有更多功能,但假设我想在 main.cpp 和 window.cpp 中使用 tListAll m_pListAll。我的 Qt 项目包含以下文件:

main.cpp //main code
window.h //header defining a class used in main
window.cpp //cpp thing defining that class's methods
peripheral.h //header file to control my peripheral device
peripheral.lib //library file to control my peripheral device (VC6 only not minGW?!)
linking.h //thing that solves(?) the minGW/VC6 library incompatibility (read on)

Scenario 1) #include <linking.h> in **only** main.cpp
Outcome: m_pListAll() only in scope of main.cpp, out of scope for window.cpp
Scenario 2) #include <linking.h> in **both** main.cpp AND window.cpp
Outcome: Redefinition errors for redefining hDLLInstance and m_pListAll().

为什么我要使用这个奇怪的 HINSTANCE 东西?与我的 .lib 文件与 minGW 不兼容有关。如果我将库静态添加为编译的一部分,我会得到: :-1: 错误:没有规则可以制作目标 'C:/Users/Joey/Documents/ValvePermissions/libLabJackU.a',这是 'release\ValvePermissions 所需的。可执行程序'。停止。

我应该怎么办?我只是希望该函数在 window.cpp 的范围内,但由于错误,我不想使用该标头两次。

4

1 回答 1

0

你的问题是你已经在标题中定义 hDLLInstance了,而m_pListAll不是简单地声明它们;因此,每个包含此标头的翻译单元都将为这些变量中的每一个创建一个公共实现,所有这些变量都在链接时发生冲突。

您需要extern在标题中的每个定义中添加关键字,从而将它们转换为声明并将您的原始定义(即没有extern关键字)复制到您的一个翻译单元中,(main.cpp也许),以便有正是在链接时定义的一种实现。因此,在您的标题中,您有:

//Declare a variable to hold a handle to the loaded DLL.
extern HINSTANCE hDLLInstance;

//Declare variables for the UD functions.
extern tListAll m_pListAll;

main.cpp, (例如):

//Define a variable to hold a handle to the loaded DLL.
HINSTANCE hDLLInstance;

//Define variables for the UD functions.
tListAll m_pListAll;
于 2015-04-14T06:39:45.130 回答