innova
innova

Reputation: 143

'Link error: already defined' when using COM interface

I'm writing a Win32 C++ Console application in VS2013 that uses a COM DLL library. I've added the files:

to my project.

Initially I started working in one file with code that looks like this:

Main.cpp

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

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

This code runs fine, I'm able to construct the COM object interface and call methods on it. However now that I'm moving forward I want to move the COM object interface setup to a different class. When trying to do this I get code like this:

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
}

This will not compile and gives me several linker errors that look like:

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

I've tried moving the #include in the Main.cpp to a Main.h and that did not help. I've tried looking inside the COMObject_i files and I found the various things that are being defined more than once but as the files are auto-generated I'm not sure how to fix the problem?

Upvotes: 0

Views: 159

Answers (1)

M.M
M.M

Reputation: 141618

Do not do:

#include "COMObject_i.c"

Instead, add COMObject_i.c as a file to your project.

.c or .cpp files should be compiled separately, not #include d. Especially, a C file should not be included in a C++ file!

It will probably "work" in this case , to include it just from main.cpp, but that is poor style.

Upvotes: 1

Related Questions