I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:
main.h
#include "other.h"
#define MAX_GROUPS 100
struct Cat
{
int something[MAX_GROUPS];
}
In other.h I also need to use MAX_GROUPS, so do I also define MAX_GROUPS in other.h like this:
other.h
#define MAX_GROUPS 100
struct Other
{
int taco[MAX_GROUPS];
}
The problem is that I'm defining a constant more than one place. I want to keep it all together.
Alternatively, do I reinclude main.h?
other.h
#include "main.h"
struct Other
{
int taco[MAX_GROUPS];
}
The problem here I think its that is creates like a circular dependancy thing. main.h includes other.h which includes main.h which includes other.h which includes etc...
What is the best way to setup the defines and includes for a project so that things sorta cascade down to other included files? Is it common practice to simply do all your defines before your includes?
Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.
To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems with multiple definitions, use include guards:
#ifndef HEADER_THING_H
#define HEADER_THING_H
/* Rest of the header file goes here. */
#endif
That way if it is already included, it is harmless.
Because main.h #includes other.h, it doesn't need to #define MAX_GROUPS again. It'll pick up that definition from the inclusion.
Generally, you should put the defines inside whichever header is relevant -- or where it is primarily used. In this case, you should put MAX_GROUPS inside other.h. By including other.h in main.h, the define will also be picked up (as mentioned by jwismar).
For bigger projects, however, you'd be better off creating a header file containing only your manifest constants (defines) and just include that where needed.
You could also protect your constants against redefinition case by case...
#ifndef MAX_GROUPS
#define MAX_GROUPS 100
#endif
Related
Example:
#ifndef HEADER_h
#define HEADER_h
#endif
Instead of HEADER_h, can I do the following?
#ifndef HEADER
or
#ifndef LIBRARY
or
#ifndef SOMETHING
or
#ifndef ANOTHERTHING
etc.
Header guards are just a convention, a "trick", making use of preprocessor conditions. In using a header guard you are creating a macro with a name, and checking whether that macro was already defined.
There is nothing magical about this macro that binds it to the filename of a header, and as such you can call it whatever you want (within reason).
That doesn't mean that you should write #ifndef URGLEBURGLE, though. You want the name to be useful and unique, otherwise there's not much point.
Typically something like #ifndef [PROJECTNAME]_[FILENAME]_INCLUDED is a good idea.
Yes, you can name the include guard symbol whatever you want, but bear in mind that they are supposed to be unique across headers. You definitely don't want a header
// first.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void foo();
#endif
and another one
// second.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void bar();
#endif
When you include both in one translation unit, one will "win" and its declarations will be visible, e.g.
// main.cpp
#include "first.h" // now, NON_UNIQUE_H is defined
#include "second.h" // NON_UNIQUE_H already there, doesn't do anything
int main(int, char**)
{
bar(); // error, won't compile, bar() isn't declared
}
Besides the necessity to circumvent such scenarios, it's best to stick to some convention throughout your project. One classical way of doing it is to convert the header file base name to upper case and append _H. If you have header files with the same base name in different directories, you can include the directory name, e.g. SUBDIR_FOO_H and OTHERSUBDIR_FOO_H. But this is up to you.
You can use a construction like
#if !defined(HEADER) || !defined(LIBRARY)
At your question, you are using
#ifndef HEADER_h
#define HEADER_h
#endif
It's the same as "#pragma once"
And yes, you can use different names of defines. In your case, LIBRARY, SOMETHING, HEADER_h - defines, that you can set in code(#define MY_VAR_NAME) or via compiler options(flag -DMY_VAR_NAME).
Your example is a so-called header guard that allows us to ensure the contents of the header are included only once. However, that is not the only use of #ifndef.You can use #ifndef for conditional compilation as in
#ifndef NO_DEBUG
do_some_debug_stuff();
#endif
So it is not only for header guards, but in general you have to carefully choose the name of the symbols you are introducing to prevent they are clashing with symbols defined elsewhere. It is just that header guards are so common that certain conventions exist (eg using FOLDER_FILENAME_H is usually sufficient to ensure uniqueness). And you need to be aware that certain names are reserved (eg starting with two underscores or underscore followed by capital letter).
What is the best location for a file include in C++? For example:
/*Foo.h*/
#include <string> //Should I place this between the #ifndef #endif?
#include "FooBar.h"
using namespace std;
#ifndef Foo_class
#define Foo_class
class Foo
{
/*XXX*/
}
#endif
/*FooBar.h*/
#ifndef FooBar_class
#define FooBar_class
class FooBar
{
/*XXX*/
}
#endif
/*Foo.cpp*/
#include "Foo.h"
/*XXX*/
/*FooBar.cpp*/
#include "FooBar.h"
/*XXX*/
Should I place the include between the define so that it only gets included when needed? Does it have impact to the system when you don't do that?
Generally, system header files do have protection against erroneous over-including, so this really doesn't matter.
#ifndef Foo_class
#define Foo_class
This pair should always be the first pair of lines of any .h file.
If you are including other .h files or library files which are include guarded, it may not matter, but a good habit nonetheless.
Another good habit, avoid using namespace std; in headers.
Library header files already contain their own #ifdef's so everything is resolved if included in multiple files. So it doesnt matter where you put it.
The best place is at the top.
Only do things different from other people when there is a technical reason to do so.
In this case:
- There is no technical difference between the two, as other answers have pointed out.
- All code I've encountered puts the include guards at the top. Although sometimes they are after the copyright notice, the guards are never after other #includes.
Therefore: put it at the top.
In most cases, it makes no real difference, as long as the inner included file has include guards. Put it where you think makes the most sense!
However, there is a reason for the convention of putting it inside the #ifndef GUARD and that is, when files take a long time load (e.g. they are on a heavily loaded network drive, or on a slow disk), in a large project, the same header file may be included many times in the same project
Let's say we have a "common.h":
#include <iostream>
#include "lesser_common.h"
#include "not_so_common.h"
#ifndef COMMON_H
#define COMMON_H
... stuff goes here ...
#endif
in main.c, we have
#include <iostream>
#incldue "common.h"
#include "myheader1.h"
#include "myheader2.h"
#include "myheader3.h"
Where myheader{1,2,3}.h also include common.h.
Now in theory, the preprocessor will have to read through all of common.h four times, and iostream 5 times. If we move the include guard out, so that when common.h is included, it doesn't include other files, at least we save the three reads of iostream. For a large project, with a huge number of files that include a large number of other files [particularly if you subscribe to the principle of "you shouldn't have to include some other file before using this one"], this can add up to quite a bit of file-reading. It shouldn't be your main choice of how/where you arrange files, but keeping it in mind a little bit is a good idea.
Having said that, most preprocessors are "clever", and understand if the file has include guards at top and bottom the first time around, it doesn't need to read the header the next time.
Also, not including files into your header files unless it's acutally needed is a very good idea - same applies for source files, of course.
I'm currently studying for a CS course's final exam and I've run into a minor (maybe major?) issue regarding the syntax of C++ #ifndef.
I've looked at the syntax for #infndef when using it as an #include guard, and most on the web seem to say:
#ifndef HEADER_H
#define "header.h"
...
#endif
But my class's tutorial slides show examples as:
#ifndef __HEADER_H__
#define "header.h"
...
#endif
I was wondering what (if any) the difference was between the two. The exam will most likely ask me to write an #include guard, and I know conventional wisdom is to just go with what the prof / tutor says, but if there's a difference during compilation I'd like to know.
The usual practice is to do neither, and put the include guard inside the header file, as it reduces repetition. e.g.:
header.h
#ifndef HEADER_H
#define HEADER_H
// Rest of header file contents go here
#endif
Precisely what you use as the macro name is down to your particular coding standard. However, there are various subtle rules in the C and C++ standards that prevent you from using identifiers beginning with underscores,1 so you should avoid __HEADER_H__, just to be on the safe side.
It's also worth mentioning that you should pick something that's unlikely to clash with anything else in your codebase. For example, if you happened to have a variable called HEADER_H elsewhere (unlikely, I realise), then you'd end up with some infuriating errors.
1. See e.g. section 7.1.3 of the C99 standard.
Names starting with a double underscore are reserved for the implementation, so I would advise against using __SOMETHING in your include guards. Also, try to chose names that make clashes unlikely. So it seems your class' tutorials are wrong on at least two counts. See this humorous article for example.
An argument for putting the include guards in the file that includes the header, rather than in the header itself, is that if the file has already been included the compiler (specifically the preprocessor) doesn't have to open and read the include file again.
That's a weak argument. In practice, the time saved is trivial, and the potential for error is large.
In your example:
#ifndef HEADER_H
#include "header.h"
...
#endif
you don't show us the #define HEADER_H. Is it somewhere in header.h? If so, how do you know that the author of header.h chose to use HEADER_H as the name of the include guard macro? What if it changes to something else later?
If you decide to put the include guard in the including file, you should define the macro there as well:
#ifndef HEADER_H
#include "header.h"
#define HEADER_H
#endif
But, as other answers have already said, it's much better to put the guard in the header itself:
header.h :
#ifndef HEADER_H
#define HEADER_H
/* contents of header.h */
#endif
and then the include simply has:
#include "header.h"
and has one less piece of information to worry about.
There's no difference if you don't use underscore in variable names anywhere else, it's only a naming convention.
You just need to put something unique.
I have 3 classes (it could be 300) , each one with its own header and implementation.
I'd like to write an 'elegant' way to organize the way I load of any class needed by every class of the three. Maybe this example helps...
I have : class1 class2 class3
Every header has:
#ifndef CLASS#_H
#define CLASS#_H
#define FORWARD_STYLE
#include "general.h"
#endif
Every implementation has:
#define DIRECT_STYLE
#include "general.h"
OK
I'm going to write a 'general.h' file in which I'd have :
#ifndef DIRECT_STYLE
#ifndef CLASS1_H
#include "class1.h"
#endif
#ifndef CLASS2_H
#include "class2.h"
#endif
#ifndef CLASS3_H
#include "class3.h"
#endif
#endif
#ifndef FORWARD_STYLE
class Class1;
class Class2;
class Class3;
#endif
// a lot of other elements needed
#include <string.h>
#include <stdio.h"
....
#include <vector.h"
( all the class I need now and in the future )
This is a good structure ? Or I'm doing some idiot thing ?
My goal is having one unique 'general.h' file to write all the elemenst I need...
Are this to work fine ?
Thanks
The basic rules to follow are:
Let each of your source file include all the header files it needs for getting compiled in a standalone manner. Avoid letting the header files include in the source file indirectly through other files.
If you have constructs which will be needed across most source files then put them in a common header and include the header in Only in those source files which need it.
Use Forward declarations wherever you can.There are several restrictions of when you can get away using them,read this to know more about those scenarios.
Overall it is a good idea to avoid including unnecessary code in source files through a common header because it just results in code bloat, so try and keep it to a minimum. Including a header just actually copy pastes the entire header to your source file and Including unnecessary files has several disadvantages, namely:
Increase in compilation time
Pollution of global namespace.
Potential clash of preprocessor names.
Increase in Binary size(in some cases though not always)
This might like a fine idea now, but won't scale and should be avoided. Your general.h file will include a vast amount of files, and thus all files that include it will (a) take ages to compile or not compile at all due to memory restrictions and (b) will have to be re-compiled every time anything changes.
Directly include the headers you need in each file, and define a few forward declaration files, and you should be fine.
The #define in a header will probably be ok, but it can propagate through lots of sources and potentially cause problems. More seriously, any time general.h or any of its includes change your entire project rebuilds. For small projects this isn't an issue, for larger projects it will result in unacceptable build times.
Instead, I utilize a few guidelines:
In headers, forward declare what you can, either explicitly or with #include "blah_fwd.h" as seen in the standard library.
All headers should be able to compile on their own and not rely on the source file including something earlier. This can be easily detected by all source files always including their own header first.
In source files, include what you need (usually you can't get away with forward declarations in source files).
Also note to never use using in headers because it will pollute the global namespace.
If this seems like a lot of work, unfortunately that's because it is. This is a system inherited from C and requires some level of programmer maintenance. If you want to be able to decide at a high level what's used by your project and let the compiler/runtime figure it out, perhaps C++ isn't the right language for your project.
I have a problem regarding multiple inclusion of header file in C++ code.
Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this.
class Z { …some code… };
class X: public Z { …some code… }; //here #include header of class Z added
class Y: public Z //here #include header of class Z added as well as of X class
{
private:
X* mX; //instance of X
…some code…
};
So in this multiple definition of all methods of base class arises. How can I cope with this problem?
Using "include guards" (Wikipedia link)
#ifndef MYHEADER_H
#define MYHEADER_H
// header file contents go here...
#endif // MYHEADER_H
This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named CustomerAccount, you can call the guard CUSTOMERACCOUNT_H.
In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard:
#ifndef Z_H
#define Z_H
// Code of Z class
#endif Z_H
Now, the headers of both X and Y can include z.h safely - it will only really be included once in a .cpp file that includes both x.h and y.h and no duplication will occur.
Always keep in mind that in C and C++ what's really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just "copy-pasted" by the preprocessor into the sources files that include them.
You can also use #pragma once preprocessor directive in your header files. (There's no need to bother about #ifndef, #define, #endif).
You use what are called include guards or header guards. They go something like this:
// within some_header.h
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
// stuff goes here
#endif
Essentially, the first time around the macro hasn't been defined so everything inside is included. However, after the first time subsequent includes will have no effect.
The naming scheme, like all naming schemes, is completely arbitrary and up to you. I like to include the file name as a minimum, as I did above, in that fashion. I also include namespaces and project names in my real projects.
There are a couple of things to watch out for. You might be tempted to do things like this:
#define _SOME_HEADER_H__
To obfuscate it a bit. However, names that begin with an underscore followed by a capital letter, or contain double-underscores are reserved identifiers, and you cannot use them.
Here the simple way to avoid multiple header inclusion in the project.
//MYCLASS.h
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class CMyClass
{
public:
CMyClass();
}
#endif //_MYCLASS_H_