Question

Deep down in WinDef.h there's this relic from the segmented memory era:

#define far
#define near

This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?

Was it helpful?

Solution

You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended.

The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.

OTHER TIPS

Undefine any macros you don't want after including windows.h:

#include <windows.h>
#undef near
#undef far

maybe:

#undef near
#undef far

could be dangerous though...

You probably don't want to undefined near and far everywhere. But when you need to use the variable names, you can use the following to undefine the macro locally and add it back when you are done.

#pragma push_macro("near")
#undef near
//your code here.
#pragma pop_macro ("near")

Best not to. They are defined for backwards compatibility with older code - if you got rid of them somehow and then later needed to use some of that old code you'd be broken.

One might argue that "near" and "far" are not very descriptive variable names. Have you considered simply providing additional detail in your variable name to resolve the conflict (i.e. nearest_match, furthest_match). Just a thought.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top