Is there such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
No. Preprocessing directives and macros are evaluated by the preprocessor, which completes its tasks before the code is parsed as C++. The preprocessor has no knowledge of classes or namespaces.
If you do not care about portability, the __if_exists statement in VC++ meets your needs.
There is no such thing at the preprocessing stage, so no macro.
However you can have a look at the is_class type traits available in Boost or in C++0x that enable you to take decisions at compile time.
That's not possible, but you could use your include guard constant to verify that the class has been included.
It sounds to me like it would be better to test if the header file with the class definition you're looking for has been included yet, instead of trying to see if the class exists. It's really easy to check this if you've been implementing the standard of defining a symbol for each header file, as shown:
// myfile.h
#ifndef _MYFILE_H_
#define _MYFILE_H_
// CODE
#endif // _MYFILE_H_
Your best bet though, is to just make sure your header files are being included in the right order in the first place. The easiest way to do this is to have an "overall" header file that in turn includes all the headers you will need in the correct order. Simply include that in each of the source files in your project, and you'll be good to go. This isn't necessarily the best solution, but it is the easiest.
Related
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.
The Google C++ Style Guide guide advises that macros must not be defined in a .h (header) file. What are the cons of doing it?
The preprocessor concatenates all included source files together in order. If you don't undefine a macro, it can apply to any source following where it was first defined.
Since headers are often the public API of a library, any macros you define in your headers could end up in someone else's code, doing unexpected things.
Since unexpected things are the antithesis of good software, you should either:
Not use macros (idiomatic C++ really shouldn't)
Define them in a private scope (always prefer private) or
Undefine them immediately after use (although this makes them largely useless for your own code)
The best solution depends on your use case. Include guards and other simple, safe defines are typically excluded ( function-like macros are more likely to cause problems, but you can still do something dumb like define TRUE FALSE).
You may also look into conditionally defining macros so they are present in your code but don't become part of the public API. Checking for a variable set during your build or keeping macros in a separate header allows others to optionally, explicitly, and knowingly include them, which can be convenient if the macros help avoid a lot of boilerplate.
For the same reasons that using statements should not be in header files: namespace pollution. If you want to use macros in a header file, make sure that you undefine them at the end of the header, this way they will not be included erroneously. If you simply want to define them in a header and use them in cpp files make sure that the "macros.h" is never included in any header.
The who point of this is that a end user of what ever public API you are developing may not want or expect, for example, sum(a, b) to expand to (a) + (b). Finding the source of one's own macro error can be a nightmare, finding someone else can be almost impossible.
I have a special macro defined in macro.h, but I want it to be valid only in part of my source files (h/cpp),
how can I do that?
I am afraid that some "bad" user included the macro.h before the source files that must not be familiar with the macro.
how can I prevent it?
It is possible to have macros that are defined only in a files scope by using #undef. E.g. :
#define MACRO 1
int a = MACRO;
#undef MACRO
int b = MACRO; // ERROR
However, this does not work across files unless you rely on the order of includes, which would be bad.
If you want to use macros defined in a macro.h in sources, you could have a second unmacro.h and include that at the end of the source:
// foo.cpp
// other includes
#include "macro.h"
// no other includes!
// contents of the source
#include "unmacro.h"
However, I would not recommended it because it is error-prone. Better reconsider if you need to use macros at all. In modern C++ their valid uses are extremely rare.
You can't. If it's in macro.h, and that file is public, there's no going around it.
A common technique is defining the macro conditionally:
#ifdef SOME_CONDITION
#define MY_MACRO
#endif
but a "bad" user can just as well define SOME_CONDITION.
What you should do is separate public headers from private ones. As you stated the problem, the macro you want hidden probably shouldn't be in a public header at all.
You cannot control the area of effect of the macro, especially if you have it in a .h which is included everywhere.
If you want it to exist only in a few .h and .cpp files then one option is to (re)define it at the top of those cpp files. You could also seperate just these macros into its own .h and include it only in the cpp files that need it and not expose it to users of your code.
You might want to give a more specific example if you want more specific answers
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 such macro in C++ (cross-compiler or compiler-specific):
#if isclass(NameSpace::MyClass)
Would be useful.
No. Preprocessing directives and macros are evaluated by the preprocessor, which completes its tasks before the code is parsed as C++. The preprocessor has no knowledge of classes or namespaces.
If you do not care about portability, the __if_exists statement in VC++ meets your needs.
There is no such thing at the preprocessing stage, so no macro.
However you can have a look at the is_class type traits available in Boost or in C++0x that enable you to take decisions at compile time.
That's not possible, but you could use your include guard constant to verify that the class has been included.
It sounds to me like it would be better to test if the header file with the class definition you're looking for has been included yet, instead of trying to see if the class exists. It's really easy to check this if you've been implementing the standard of defining a symbol for each header file, as shown:
// myfile.h
#ifndef _MYFILE_H_
#define _MYFILE_H_
// CODE
#endif // _MYFILE_H_
Your best bet though, is to just make sure your header files are being included in the right order in the first place. The easiest way to do this is to have an "overall" header file that in turn includes all the headers you will need in the correct order. Simply include that in each of the source files in your project, and you'll be good to go. This isn't necessarily the best solution, but it is the easiest.