June 12th, 2007

Fixing COM Interface Redefinition Error

Hello my name is Steven Toscano and I work on the Visual C++ IDE team.  Recently we had a customer visit that exposed a common problem people are seeing when migrating to VS2005 from older versions of VS.

 

You will encounter this problem if you have defined an interface with the same name as one of the interfaces introduced in the Visual Studio 2005 VC++ or Platform SDK headers.  There are different approaches to this problem depending on what you are trying to upgrade.

 

Upgrading a server without touching existing clients

 

Scenario:

Your server defines an interface which conflicts with one that is pulled in by standard windows headers.  Your clients depend on this interface name.  For example let’s say you’ve named your interface IContext, it will conflict with the interface defined in ObjIdl.h that comes with the Platform SDK.  When you build you get errors about your COM object not implementing enough methods in IContext it’s because the compiler is picking up the interface from the Platfom SDK headers first instead of yours.

 

Solution #1:

Usually the headers that are pulling in these duplicate names are in your stdafx.h file.  To prevent the compiler from pulling in the interface definition from the VS2005 headers insert the following code at the top of your stdafx.h:

 

#define __IContext_FWD_DEFINED__

#define __IContext_INTERFACE_DEFINED__

 

Then at the end of your stdafx.h file insert this code:

 

#undef __IContext_FWD_DEFINED__

#undef __IContext_INTERFACE_DEFINED__

 

This is to get the compiler to choose your interface and ignore the VS2005 one.  Your interface declaration usually comes from your .h file generated by midl after compiling your .IDL file.

 

Solution #2:

If you are getting an earlier error running midl similar to:

 

error MIDL2003 : redefinition : IContext

 

This means that your IDL file that contains the definitions of your COM object has a conflicting interface name.  The above solution alone will not work for you.  You will need to rename the conflicting type in your IDL file.  For example let’s say the name is IContext, search for all instances of IContext and replace with IContext2 in your IDL file.  Then in your server implementation code anywhere you include the generated .h file add this code:

 

typedef IContext2 IContext;

#define IID_IContext IID_IContext2

 

This way you won’t need to change any of your server implementation code and old clients will still be able to connect to you using the IContext name.  Before you can build successfully add the workaround described in solution #1 above so that you don’t get a redefinition error on IContext with the one in ObjIdl.h.  Now you should be able to build successfully and old clients should be able to connect to you (provided you didn’t change anything else).

Category
C++

0 comments

Discussion are closed.