开发者

C++ declared constant named the same as a defined constant

Is there a standard or good way of avoiding declared constants being named the same as a defined constant.

My Problem,

Im trying to compile my program using autoconf in linux which defines VERSION but in one 开发者_运维知识库of Mongo's db header files they declare a constant named VERSION. There's obviously a problem naming a variable using a right hand value.

Normally I would just change the name but in this case its not my library. I could figure out how to rename the defined variable autoconf.

Any suggestions?


You have to use no-define along with AM_INIT_AUTOMAKE in your configure.ac file.

By default this macro AC_DEFINE's PACKAGE and VERSION. This can be avoided by passing the no-define option, as in:

AM_INIT_AUTOMAKE([gnits 1.5 no-define dist-bzip2])

See Automake manual.


If you've localized the error, you can do something like this:

const unsigned int OLD_VERSION = VERSION;
#undef VERSION
#include <mongodb_header.h>

and then use OLD_VERSION in your code, instead of VERSION. Or just define your version in another namespace.

Also, file a bug in Mongodb. This is not the correct behavior of using just VERSION as a name in the outer namespace. It should check at least if VERSION is already defined, or prefix the variable such as MONGODB_VERSION, or something like that.


In general there's no good way to safeguard yourself against what some 3rd party library might pollute the global namespace with. This is why god invented namespaces.

You can use namespaces if VERSION is a global symbol known at compile time:

namespace yourStuff
{
    int VERSION;

    // references to VERSION here refer to the inner VERSION, not ::VERSION
}

but if VERSION is a preprocessor macro (as I suspect with its capitalization) then it doesn't follow any compilation rules and exists outside the rules of the compiler. You can detect it with other preprocessor macros:

#ifdef VERSION
 // define it to be something else
#else
#endif

(or use #undef like in Diego's answer to kill it)

But doing that everywhere VERSION is references will get nasty. You'll just need to not use VERSION.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜