'Link error: already defined' when using COM interface

'Link error: already defined' when using COM interface

我正在 VS2013 中编写一个使用 COM DLL 库的 Win32 C++ 控制台应用程序。我已经添加了文件:

到我的项目。

最初我开始在一个文件中工作,代码如下所示:

Main.cpp

#include "COMObject_i.h"
#include "COMObject_i.c"

int _tmain(int argc, _TCHAR* argv[])
{
    // Setup and use COM object interface...
}

这段代码运行良好,我能够构造 COM 对象接口并调用它的方法。 但是,既然我要向前迈进,我想将 COM 对象接口设置移动到不同的 class。尝试这样做时,我得到这样的代码:

COMObjectWrapper.h

#pragma once

#include "COMObject_i.h"
#include "COMObject_i.c"

class COMObjectWrapper
{
     // Class declaration
}

COMObjectWrapper.cpp

#include "COMObjectWrapper.h"

// Class method definitions

Main.cpp

#include "COMObjectWrapper.h"

int _tmain(int argc, _TCHAR* argv[])
{
    // Use COM object wrapper
}

这将无法编译并给我几个看起来像这样的链接器错误:

error LNK2005: _CLSID_COMObjectInterface already defined in COMObjectWrapper.obj
error LNK2005: _IID_ICOMObjectInterface already defined in COMObjectWrapper.obj
error LNK2005: _LIBID_ICOMObjectLib already defined in COMObjectWrapper.obj

我试过将 Main.cpp 中的 #include 移动到 Main.h 中,但没有帮助。我尝试查看 COMObject_i 文件,我发现不止一次定义了各种东西,但由于文件是自动生成的,我不确定如何解决这个问题?

不做:

#include "COMObject_i.c"

相反,将 COMObject_i.c 作为文件添加到您的项目中。

.c.cpp 文件应该单独编译,而不是 #include d.特别是,C 文件不应包含在 C++ 文件中!

在这种情况下,可能 "work" 只包含 main.cpp,但这是糟糕的风格。