Is it possible to avoid C++ compiler error (C2757) where 2 different header files contain same symbol for namespace & class?
I am facing a problem when implementing some new code to an existing library. This library already references a class with a name say 'foo开发者_开发百科'. The same name is used as a namespace in the other header file which has to be included to implement the new functionality. Since both the header files are a part of legacy code libraries I cannot amend them. So here I am looking for any way so as to avoid the Compiler Error (C2757: a symbol with this name already exists and therefore this name cannot be used as a namespace name). I am not sure whether it is possible or not. Hence, Any help shall be appreciated. Thanks
For clarity here is the sample code illustration for the issue:
HeaderA.h
class foo
{}
HeaderB.h
namespace foo
{
class ABC{}
}
HeaderC.h
#include <HeaderA.h>
#include <HeaderB.h>
using namespace foo;
class Toimplement{
ABC a; //Throws Error C2757
}
You can try the following workaround:
namespace bar {
#include "HeaderA.h"
}
#include "HeaderB.h"
...
bar::foo fooObject;
foo::ABC abcObject;
Include one of header file in new namespace.
namespace headerb {
#include <HeaderB.h>
}
...
...
headerb::ABC a1;
ABC b2;
In your example, the simplest approach is to not include HeaderA.h
in HeaderC.h
. The class foo isn't needed in Toimplement.
so let's assume you need the visibility of both files, and you want to link to the symbols included by HeaderA:
// header a
class FOO {};
// followed by a file with your declarations/disambiguators
typedef FOO wwlib_FOO;
// header b
namespace FOO {class ABC {};}
// followed by a file with your declarations/disambiguators
namespace vvlib_FOO = FOO;
// and finally usage
using namespace FOO; // note: using `using` is a good way to introduce complications like this one
void fn() {
class FOO t;
wwlib_FOO t2(t);
vvlib_FOO::ABC abc;
...
the namespace trick won't work, apart from very very simple cases (unless it's entirely templates or inlines, which is very unusual). you'll just end up with duplicated code, classes that you can't pass around, and missing references at link-time.
精彩评论