Can I redefine a C++ macro then define it back? - c++

I am using both the JUCE Library and a number of Boost headers in my code. Juce defines "T" as a macro (groan), and Boost often uses "T" in it's template definitions. The result is that if you somehow include the JUCE headers before the Boost headers the preprocessor expands the JUCE macro in the Boost code, and then the compiler gets hopelessly lost.
Keeping my includes in the right order isn't hard most of the time, but it can get tricky when you have a JUCE class that includes some other classes and somewhere up the chain one file includes Boost, and if any of the files before it needed a JUCE include you're in trouble.
My initial hope at fixing this was to
#undef T
before any includes for Boost. But the problem is, if I don't re-define it, then other code gets confused that "T" is not declared.
I then thought that maybe I could do some circular #define trickery like so:
// some includes up here
#define ___T___ T
#undef T
// include boost headers here
#define T ___T___
#undef ___T___
Ugly, but I thought it may work.
Sadly no. I get errors in places using "T" as a macro that
'___T___' was not declared in this scope.
Is there a way to make these two libraries work reliably together?

As greyfade pointed out, your ___T___ trick doesn't work because the preprocessor is a pretty simple creature. An alternative approach is to use pragma directives:
// juice includes here
#pragma push_macro("T")
#undef T
// include boost headers here
#pragma pop_macro("T")
That should work in MSVC++ and GCC has added support for pop_macro and push_macro for compatibility with it. Technically it is implementation-dependent though, but I don't think there's a standard way of temporarily suppressing the definition.

Can you wrap the offending library in another include and trap the #define T inside?
eg:
JUICE_wrapper.h:
#include "juice.h"
#undef T
main.cpp:
#include "JUICE_wrapper.h"
#include "boost.h"
rest of code....

I then thought that maybe I could do some circular #define trickery like so:
The C Preprocessor doesn't work this way. Preprocessor symbols aren't defined in the same sense that a symbol is given meaning when, e.g., you define a function.
It might help to think of the preprocessor as a text-replace engine. When a symbol is defined, it's treated as a straight-up text-replace until the end of the file or until it's undefined. Its value is not stored anywhere, and so, can't be copied. Therefore, the only way to restore the definition of T after you've #undefed it is to completely reproduce its value in a new #define later in your code.
The best you can do is to simply not use Boost or petition the developers of JUCE to not use T as a macro. (Or, worst case, fix it yourself by changing the name of the macro.)

Related

Need clarification on #ifndef #define

The code I am working has multiple headers and source files for different classes face.cc, face.hh, cell.cc, cell.hh edge.cc edge.hh and the headers contain includes like this,
#ifndef cellINCLUDED
#define cellINCLUDED
#ifndef faceINCLUDED
#define faceINCLUDED
I saw through http://www.cplusplus.com/forum/articles/10627/ and saw the way to write include guard is
#ifndef __MYCLASS_H_INCLUDED__
#define __MYCLASS_H_INCLUDED__
So in above code that I am working on, does compiler automatically understands it is looking for face.hh or cell.hh files?
better question : Is writing __CELL_H_INCLUDED__ same as cellINCLUDED ?
#ifndef __MYCLASS_H_INCLUDED__
#define __MYCLASS_H_INCLUDED__
So in above code that I am working on, does compiler automatically
understands it is looking for face.hh or cell.hh files?
No, the compiler doesn't automatically understand what you mean.
What really happens is that, when compiling a translation unit, the Compiler holds a list of globally defined MACROs. And so, what you are doing is defining the MACRO __MYCLASS_H_INCLUDED__ if it doesn't already exists.
If that macro is defined, that #ifndef until #endif will not be parsed by the actual compiler.
Hence you can test for the existence of that MACRO to determine if the Compiler has parsed that header file to include it once and only once in the translation unit... This is because the compiler compiles each translation unit as one flattened file (after merging all the #includes)
See https://en.wikipedia.org/wiki/Include_guard
Is writing __CELL_H_INCLUDED__ same as cellINCLUDED ?
Yes it is.... The reason some prefer using underscored prefixed and suffixed MACROs for include guards is because they have extremely low probability of ever being used as identifiers... but again, underscore could clash with the compiler...
I prefer something like this: CELL_H_INCLUDED
If you use cellINCLUDED, there are chances that someday, somebody may use it as an identifier in that translation unit
The preprocessor definitions have no special meaning. The only requirement is that they stay unique across the modules, and that's why the file name is typically a part of them.
In particular, the mechanics for preventing double inclusion aren't "baked in" the language and simply use the mechanics of the preprocessor.
That being said, every compiler worth attention nowadays supports #pragma once, and you could probably settle on that.
As the link you have referenced says, "compilers do not have brains of their own" - so to answer your question, no, the compile does not understand which particular files are involved. It would not even understand that '__cellINCLUDED' has anything conceptually to do with a specific file.
Instead, the include guard simply prevents the logic contained between its opening #ifndef and closing #endif from being included multiple times. You, as the programmer, are telling the compiler not to include that code multiple times - the compiler is not doing anything 'intelligent' on its own.
Nope, This is essentially telling the compiler/parser that if this has already been put into the program, don't puthave already been loaded.
This should be at the top (and have an #endif at the bottom) of your .h file.
Lets say you have mainProgram.cpp and Tools.cpp, with each of these files loading fileReader.h.
As the compiler compiles each cpp file it will attempt to load the fileReader.h. unless you tell it not to it will load all of the fileReader file in twice.
ifndef = if not defined
so when you use these (and the #endif AFTER all your code in the .h file)
you are saying:
if not defined: cellINCLUDED
then define: cellINCLUDED with the following code:
[code]
end of code
so this way when it goes to load the code in your .h file a second time it hits the if not defined bit and ignores the code on the second time.
This reduces compile time and also means if you are using a poor/old compiler it isn't trying to shove the code in again.

#define Conflicting with Conditionally #include-d Library

Here's a simplified example. Suppose I'm writing program A using libraries B and C. Niether library's source code can be changed and they are the only available libraries for the purpose. Library B has a reasonable #define whereas Library C has a stupid #define that aliases it. Something like, say:
//library_b_header.hpp
#pragma once
#define uint16 unsigned short
//...
//library_c_header.hpp
#pragma once
#define uint16 unsigned char
Most of the precedent I have is questions like this. One answer helpfully suggests, covering the range of suggestions I've seen (paraphrasing):
Add #undef in your own code
Don't directly include library_c_header.hpp. If another library includes it for you, don't include that directly. Instead, include it in a separate .cpp file, which can then expose wrapper functions in its header.
Rename your own symbol.
The second option is close to my normal solution, but library C is huge; I can't possibly wrap all the functionality. Even if I could, there's a good chance of screwing up, and it's certainly not portable to new releases of library C (which are also frequent).
The third option doesn't work, since this is used everywhere. It's not just me that this is conflicting with; it's conflicting with literally everything else. I suppose it could be done . . . it's just a MORALLY WRONG #define, AND IT SHOULD DIE!
The first option here is closest to what I'm trying. The second issue is that #includeing library C depends on a token defined in library B.
The furthest I've gotten is:
#include <library_b/library_b_header.hpp>
#define library_b_uint16 uint16
#undef uint16
#ifdef LIBRARY_B_SYMBOL
#include <library_c/library_c_header.hpp>
#undef uint16
#define uint16 library_b_uint16
#endif
This clearly doesn't work, but perhaps it expresses my intent. Is there anything else I could try?
If your compiler supports the push_macro and pop_macro pragmas, you may be able to use them like so:
#include <library_b/library_b_header.hpp>
#pragma push_macro("uint16")
#undef uint16
#include <library_c/library_c_header.hpp>
#pragma pop_macro("uint16")
(These pragmas are nonstandard, but they are widely supported. Visual C++, gcc, clang, and the Intel C++ Compiler all support them.)
Yes, you need to do this everywhere you include a header from Library C that defines this macro, but this is usually simplified by writing your own header that wraps inclusion of the Library C headers, then including that header wherever Library C is needed in your project.

Is the _HAVE_BOOST macro a built-in in C++? Where does it come from?

I'm reading a piece of code that seems like it optionally uses the C++ Boost library. It is as follows:
#ifdef _HAVE_BOOST
#include <boost/random.hpp>
#endif
Later on in the code, there are several statements that depend on this "_HAVE_BOOST". I presume that _HAVE_BOOST is simply a flag that is set to true, if the C++ library is properly imported.
Is the "_HAVE_BOOST" flag a built-in part of C++ ifdef syntax? That is, I tried Googling for this flag but didn't find any documentation. Also, at the head of the file, no #include<boost> is present. It looks like this boost functionality is deprecated throughout the file -- would _HAVE_BOOST be set to true if this #include<boost> were added?
Is there a list or documentation somewhere for describing the kinds of capital letters that go along with #ifdef?
I presume that _HAVE_BOOST is simply a flag that is set to true...
#ifdef _HAVE_BOOST does not test whether _HAVE_BOOST is true; It test whether such preprocessor macro is defined at all, regardless of the value.
...if the C++ library is properly imported.
Yes, considering the context, this particular macro is probably meant to signify, whether Boost is available or not and thus, whether it's possible to depend on it.
Is there a list or documentation somewhere for describing the kinds of capital letters that go along with #ifdef?
Macros can be defined with either #define directive in a header file or, in the compilation command (See the -D option for gcc for example). Compilers may also predefine some macros as well.
Any header file can define macros. You should usually be able to find which macros may be defined by reading the documentation, or if you don't have documentation, by reading the header files themselves.
would _HAVE_BOOST be set to true if this #include were added?
I find it unlikely that it would be defined in <boost> itself. After all, testing if Boost is available after you try to include it would be rather pointless.
When is _HAVE_BOOST defined?
You should ask that from the person who wrote the code. Another question to ponder is, is it defined at all? If it isn't, then the code between the ifdefs is removed by the preprocessor.
My crystal ball tells me that it's probably supposed to be defined by some sort of configuration script for the build process. For example, autoconf has a macro that will define a preprocessor macro HAVE_header-file if a header exists. Note the lack of underscore at the beginning.
this just means that if you define a preprocessor macro "_HAVE_BOOST" the compiler will include boost/random.hpp. Like this:
#define _HAVE_BOOST
#ifdef _HAVE_BOOST
#include <boost/random.hpp>
#endif
Look here for more details about preprocessor directives.
If the compiler supports c++11, it will have <random> support.
With some clever use of indirect includes and typedefs (or using statements ?!) it could be made to work with or without boost for random.

Is there any situation where you wouldn't want include guards?

I know why include guards exist, and that #pragma once is not standard and thus not supported by all compilers etc.
My question is of a different kind:
Is there any sensible reason to ever not have them? I've yet to come across a situation where theoretically, there would be any benefit of not providing include guards in a file that is meant to be included somewhere else. Does anyone have an example where there is an actual benefit of not having them?
The reason I ask - to me they seem pretty redundant, as you always use them, and that the behaviour of #pragma once could as well just be automatically applied to literally everything.
I've seen headers that generate code depending on macros defined before their inclusion. In this case it's sometimes wanted to define those macros to one (set of) value(s), include the header, redefine the macros, and include again.
Everybody who sees such agrees that it's ugly and best avoided, but sometimes (like if the code in said headers is generated by some other means) it's the lesser evil to do that.
Other than that, I can't think of a reason.
#sbi already talked about code generation, so let me give an example.
Say that you have an enumeration of a lot of items, and that you would like to generate a bunch of functions for each of its elements...
One solution is to use this multiple inclusion trick.
// myenumeration.td
MY_ENUMERATION_META_FUNCTION(Item1)
MY_ENUMERATION_META_FUNCTION(Item2)
MY_ENUMERATION_META_FUNCTION(Item3)
MY_ENUMERATION_META_FUNCTION(Item4)
MY_ENUMERATION_META_FUNCTION(Item5)
Then people just use it like so:
#define MY_ENUMERATION_META_FUNCTION(Item_) \
case Item_: return #Item_;
char const* print(MyEnum i)
{
switch(i) {
#include "myenumeration.td"
}
__unreachable__("print");
return 0; // to shut up gcc
}
#undef MY_ENUMERATION_META_FUNCTION
Whether this is nice or hackish is up to you, but clearly it is useful not to have to crawl through all the utilities functions each time a new value is added to the enum.
<cassert>
<assert.h>
"The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h> is included."
It can be a problem if you have two headers in a project which use the same include guard, e.g. if you have two third party libraries, and they both have a header which uses an include guard symbol such as __CONSTANTS_H__, then you won't be able to successfully #include both headers in a given compilation unit. A better solution is #pragma once, but some older compilers do not support this.
Suppose you have a third party library, and you can't modify its code. Now suppose including files from this library generates compiler warnings. You would normally want to compile your own code at high warning levels, but doing so would generate a large set of warnings from using the library. You could write warning disabler/enabler headers that you could then wrap around the third party library, and they should be able to be included multiple times.
Another more sophisticated kind of use is Boost's Preprocessor iteration construct:
http://www.boost.org/doc/libs/1_46_0/libs/preprocessor/doc/index.html
The problem with #pragma once, and the reason it is not part of the standard, is that it just doesn't always work everywhere. How does the compiler know if two files are the same file or not, if included from different paths?
Think about it, what happens if the compiler makes a mistake and fails to include a file that it should have included? What happens if it includes a file twice, that it shouldn't have? How would you fix that?
With include guards, the worst that can happen is that it takes a bit longer to compile.
Edit:
Check out this thread on comp.std.c++ "#pragma once in ISO standard yet?"
http://groups.google.com/group/comp.std.c++/browse_thread/thread/c527240043c8df92

Is there a clean way to prevent windows.h from creating a near & far macro?

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?
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.
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.