Notes On Software

C++/CLI IServiceProvider: ambiguous symbol compiler error

| 0 comments

While doing some programming using C++/CLI for .NET interop, I ran across this compiler error:

error C2872: ‘IServiceProvider’ : ambiguous symbol

As the MSDN reference indicates, the compiler can’t sort out a symbol because it encountered multiple definitions. In this case it was because of a core IServiceProvider definition that was not part of my code.

Rules to avoid this error:

Do not put “using namespace” statements in global scope in your header files

If you put using namespace declarations at the top of a header file, they are global and can lead to these ambiguous symbol compile errors.

This means instead of this in a MyClass.h file:

#pragma once

using namespace System;

public ref class MyClass
{
     IntPtr GetMyReference(String^ name);
}

you’ll need to use fully qualified references:

#pragma once

public ref class MyClass
{
     System::IntPtr GetMyReference(System::String^ name);
}
If you put “using namespace” statements in your cpp files, add them after any includes

Your MyClass.cpp file should look like this:

#include "StdAfx.h"
#include "MyClass.h"

using namespace System;

IntPtr MyClass::GetMyReference(String^ name)
{
     // provide implementation
}

Leave a Reply

Required fields are marked *.

*