I have gotten to a point in my course where they use Code::Blocks to automatically make a header file. However, I don't think it's necessary to download Code::Blocks specifically for this reason, and so I am looking for a way to make my own header files.
And so, I started my search online to find out exactly how to do this.
I checked How to create my own header file in c++? [closed] and also cplusplus.com
However, the former uses uses #ifndef YOUR_NAME_INCLUDE and #define YOUR_NAME_INCLUDE whereas the latter uses #ifndef __X_H_INCLUDED__ and #define __X_H_INCLUDED__, with 2 underscores surrounding the #ifndef and #define. How should I format my header guards? Does it really matter?
For example, if I have a file foo.h, which looks like this:
#ifndef ???
#define ???
int sum(int a, int b) {
return a + b;
}
#endif
should I put SUM_INCLUDED, FOO_INCLUDED, FOO_H instead of the ??? or something else altogether?
Second, is making a header file really as easy as just sticking a .h or .hpp to the end of it?
#ifndef FOO
#define FOO
struct foo {};
#endif
The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.
There really isn't any "magic" about an include file other than this. In fact, the extension doesn't even matter. It could be foo.h or foo.hh or just foo (like the standard library headers like vector or iostream).
Ultimately, it's personal preference how you structure your include guards. Some use __FOO__ (note this runs afoul of C++ standard regarding reserved identifiers) or FOO_H_INCLUDED (which is standard compliant) while others may elect for different patterns.
While it's not strictly standard C++, my team uses #pragma once and foregoes the ifndef/define/endif code. It's supported by all the compilers we use (gcc/msvc/clang) and you don't have drawbacks such as too different foo.h files causing one (or the other) definition to be excluded.
The same file then looks like this
#pragma once
struct foo {};
Related
When writing templated classes, I like to move the implementation into a different file (myclass.tpp) and include it at the bottom of the main header (myclass.hpp).
My Question is: do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file?
Example code:
myclass.hpp
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
template<typename T>
class MyClass
{
public:
T foo(T obj);
};
//include template implemetation
#include "myclass.tpp"
#endif
myclass.tpp
#ifndef MYCLASS_TPP //needed?
#define MYCLASS_TPP //needed?
template<typename T>
T MyClass<T>::foo(T obj)
{
return obj;
}
#endif //needed?
Do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file?
Include guards are never needed: they're just terribly useful, cheap, non-disruptive and expected. So Yes, you should protect both files with header guards:
Terribly useful: they allow you to declare a dependency from multiple files without keeping track of which files have already been included.
Cheap: this is just some precompilation tokens.
Non-disruptive: they fit well with most use-cases of #include (I've had a colleague who didn't know how to write macros so he #included implementation files facepalm).
Expected: developers know what they are and barely notice them; on the contrary a header file missing include guards wakes us up and adds to the global wtf/line counter.
I take the opportunity to highlight the comment from StoryTeller:
I'd go a step further and add a descriptive #error directive if the hpp guard is not defined. Just to offer a little protection from people including the tpp first.
Which will translate to:
#ifndef MYCLASS_TPP
#define MYCLASS_TPP
#ifndef MYCLASS_HPP
#error __FILE__ should only be included from myclass.hpp.
#endif // MYCLASS_HPP
template<typename T>
T MyClass<T>::foo(T obj)
{
return obj;
}
#endif // MYCLASS_TPP
Notice: if a translation unit first #include <myclass.hpp> and then #include <myclass.tpp>, no error is fired and everything is fine.
Just use pragma once in all headers file. The compiler will ensure your file will be included only once. The compiler may only fail to recognize in very unreasonable condition: someone structure its include directories using hard-link. Who does this? If someone cannot find a unique name for its file, why would he be more skilled to find a unique name for each include guard for all the header files?
On the other hand, include guard may be broken because the name of the macro will not be that unique, because of a copy/paste, or a header file created by first copying an other, etc...
How are chosen the unique macro name: <project name>_<filename>? How could it be more unique than a uniqueness based on the entire root directory structure?
So in the end, one should consider when choosing between include guard or pragma once, the cost of the job that is necessary to ensure uniqueness:
1 - For pragma once you only have to ensure that the directory structured of your system is not messed-out thanks to hard links.
2 - For include guard for each file on your system you should ensure that the macro name is unique.
I mean as a manager, evaluating the cost of this job and the failure risk does let only one option. Include guard are used only when no evaluation is performed: it is a non decision.
I get roughly what it does. What I don't understand is why it's not the default? What are the use cases where some header file would need to be included multiple times?
The reason it's not the default is primarily historical these days -- when the C language was formalized, #include was specified that it must act exactly as if the user had copy-and-pasted the specified file's contents at the location of the #include-line; and C++ wanted (and wants) to remain as compatible as possible with C, so C++ inherited that behavior from C.
As for a use-case where including the same header file more than once might be useful; one instance where I found it useful was for simulating a templated-container-class in C (because C doesn't support templates directly). I had a container-implementation-header-file that looked something like this (but more elaborate; I'm showing a simplified version here for readability):
// MyContainerImplemention.h
// be sure to #define MYTYPE and MYARRAYSIZE
// before #include-ing this file!
struct ArrayOf##MYTYPE
{
MYTYPE arrayOfItems[MYARRAYSIZE];
};
inline void Set##MYTYPE##Item(struct ArrayOf##MyType * container, int which, MYTYPE item)
{
container[which] = item;
}
[... and so on for various other MYTYPE-specific methods ...]
... then my .c files could do something like:
#define MYTYPE int
#define MYARRAYSIZE 10
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE
#define MYTYPE short
#define MYARRAYSIZE 15
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE
struct ArrayOfint myInts;
struct ArrayOfshort myShorts;
SetintItem(&myInts, 5, 12);
SetshortItem(&myShorts, 3, 2);
[...]
... and end up with the container "class" and its associated methods implemented for each data-type, without having to manually write a new implementation of the container "class" each time.
Yes, it was extremely ugly -- but not as ugly as having to manually write out thousands of lines of redundant container-code would have been. (The real container-implementation-header-file implemented a hash table and was several hundred lines long)
Without include guards or #pragma once the compiler would have to maintain a list of included files. This is not easy, because of different possible paths to these files (and #pragma once doesn't completely solve this) and would be expecting a bit much of the original C compilers, which had to work with very limited memory.
What's true today is not necessarily true when C came about and the C pre-processor, upon which the C++ one is based, was created.
#pragma once is just a step towards having proper C++ modules so this annoying historical legacy is finally eliminated.
Yes, it's valid to include a file multiple times, and yes, each time it's included it can behave in entirely different ways. This is why making pre-compiled headers is a huge headache for compiler developers.
Guard blocks or #pragma once are included in order to prevent a file from being included multiple times.
#pragma once, while supported on most compilers, is not an official part of the c++ standard, and may not work on every compiler. You can use a guard block, which will work on any compiler. An example of a guard block in the file MyClass.hpp would be:
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
//Code here
#endif
I was wondering if there is an elegant way to solve this problem. Suppose there's a common header eg
// common.h
#ifndef COMMON_H
#define COMMON_H
#define ENABLE_SOMETHING
//#define ENABLE_SOMETHING_ELSE
#define ENABLE_WHATEVER
// many others
#endif
Now this file is included by, let's say 100 other header files and the various #define are used to enable or disable some parts of code which are confined to just 1-2 files.
Everytime a single #define is changed the whole project seems to be rebuilt (I'm working on Xcode 5.1), which makes sense as it must be literally replaced all around the code and the compiler can't know a priori where it's used.
I'm trying to find a better way to manage this, to avoid long compilation times, as these defines are indeed changed many times. Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
So I was wondering if there is a pattern which is usually used to solve this problem, I was thinking about having
// common.h
class Enables
{
static const bool feature;
};
// common..cpp
bool Enables::feature = false;
Will this be semantically equivalent when compiling optimized binary? (eg. code inside false enables will totally disappear).
You have two distinct problems here:
Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
This is your first problem. If I undestand correctly, if you have more than one functional area, you are not interested in having to include a header for each of them (but a single header for everything).
Apply these steps:
do split the code by functionality, into different headers; Each header should contain (at most) what was enabled by a single #define FEATURESET (and be completely agnostic to the existence of the FEATURESET macro).
ensure each header is only compiled once (add #pragma once at the beginning of each feature header file)
add a convenience header file that performs #if or #ifdef based on your defined features, and includes the feature files as required:
// parsers.h
// this shouldn't be here: #pragma once
#ifdef PARSEQUUX_SAFE
#include <QuuxSafe.h>
#elif defined PARSEQUUX_FAST
#include <QuuxFast.h>
#else
#include <QuuxSafe.h>
#endif
// eventually configure static/global class factory here
// see explanation below for mentions of class factory
Client code:
#include <parsers.h> // use default Quux parser
#define PARSEQUUX_SAFE
#include <parsers.h> // use safe (but slower) Quux parser
So I was wondering if there is a pattern which is usually used to solve this problem
This is your second problem.
The canonical way to enable functionality by feature in C++, is to define feature API, in terms of base classes, class factories and programming to a generic interface.
// common.h
#pragma once
#include <Quux.h> // base Quux class
struct QuuxFactory
{
enum QuuxType { Simple, Feathered };
static std::unique_ptr<Quux> CreateQuux(int arg);
static QuuxType type;
};
// common.cpp:
#include <common.h>
#include <SimpleQuux.h> // SimpleQuux: public Quux
#include <FeatheredQuux.h> // FeatheredQuux: public Quux
std::unique_ptr<Quux> QuuxFactory::CreateQuux(int arg)
{
switch(type) {
case Simple:
return std::unique_ptr<Quux>{new SimpleQuux{arg}};
case Feathered:
return std::unique_ptr<Quux>{new FeatheredQuux{arg}};
};
// TODO: handle errors
}
Client code:
// configure behavior:
QuuxFactory::type = QuuxFactory::FeatheredQuux;
// ...
auto quux = QuuxFactory::CreateQuux(10); // creates a FeatheredQuux in this case
This has the following advantages:
it is straightforward and uses no macros
it is reusable
it provides an adequate level of abstraction
it uses no macros (as in "at all")
the actual implementations of the hypothetical Quux functionality are only included in one file (as an implementation detail, compiled only once). You can include common.h wherever you want and it will not include SimpleQuux.h and FeatheredQuux.h at all.
As a generic guideline, you should write your code, such that it requires no macros to run. If you do, you will find that any macros you want to add over it, are trivial to add. If instead you rely on macros from the start to define your API, the code will be unusable (or close to unusable) without them.
There is a way to split defines but still use one central configuration header.
main_config.h (it must not have an include guard or #pragma once, because that would cause strange results if main_config.h is included more than once in one compilation unit):
#ifdef USES_SOMETHING
#include "something_config.h"
#endif
#ifdef USES_WHATEVER
#include "whatever_config.h"
#endif
something_config.h (must not have include guards for the same reason as main_config.h):
#define ENABLE_SOMETHING
All source and header files would #include only main_config.h, but before the include they must declare what part of it would they be referring to:
some_source.cpp:
#define USES_SOMETHING
#include "main_config.h"
some_other_file.h:
#define USES_WHATEVER
#include "main_config.h"
This question is one of several that discuss naming conventions for C++ include guards. The person asking that question thinks that this naming convention:
#ifndef FOO_H
#define FOO_H
// ...
#endif
is a bit non-intuitive when taken by itself (what does FOO_H mean?) and I tend to agree.
Others say that, barring the need to add more stuff for better collision avoidance (like PROJECTNAME_FOO_H_SDFFGH69876GF), the name FOO_H is just fine because it's clear from its context what its purpose is (namely, it's at the beginning of the files of the same name and it's clear that it's an include guard).
I could buy this if the only purpose of having FOO_H would be to guard against multiple inclusion, but are there conditions for which I'd want to have FOO_H elsewhere in the files? I'd think conditional compilation would be a good reason, in which case naming it something like FOO_H_INCLUDED would be clearer.
Are there straightfoward uses akin to this, or should I avoid repurposing the include guards?
I think the question is flawed in itself. The term include guards refers to #defines and checks for #defined in the particular use of guarding against multiple inclusion, which is as much to say that is the only use for that.
Now taken a little more generally, defines and conditional compilation can be used for other things, like writing bits of code that are platform dependent and will only get compiled under some circumstances...
Whether FOO_H or FOO_H_INCLUDED is better, I will always say that the later is the most expressive, and then I will go back to vi and type FOO_H in my next foo.h header. Again, as I mentioned in a comment on the other question, you grow used to the pattern:
#ifndef XXXXXXXXX
#define XXXXXXXXX
#endif
as the first two and last line in a file and you end noticing. That is until it bites back if you have reused the same name...
Sometimes, I use this for "implementation" header files. Actual naming scheme for guards may differ.
#ifndef FOO_IMPL_H
#define FOO_IMPL_H
#ifndef FOO_H
#error Don't include this directly
#endif
// Ugly implementation of the stuff in foo.h, with an uncountable
// number of template and typename keywords
#endif
In my opinion, include guards should be include guards and nothing more. If you want conditional compilation, I would define something else. If you were throwing around #if defined(FOO_H) in your code, I think people would find this strange since _H usually indicates an include guard.
One thing I can think of though is checking if the file has already been included (duh!) so that you don't have to include the file yourself. I'm not sure if this would speed up compilation or not, in comparison to forward declarations or #pragma once
In main.cpp:
#include "bar.h" // comment this line to see the difference
#include "foo.h"
int main()
{
return 0;
}
In bar.h:
#ifndef BAR_H
#define BAR_H
class BarClass
{
};
#endif
In foo.h:
#ifndef FOO_H
#define FOO_H
#if !defined(BAR_H)
#error bar h was not included // forgot how to do compiler warnings...
#include "bar.h" // we should include the file
#else
#error bar h was included // same thing, should be changed to warning
#endif
// do something with BarClass
#endif FOO_H
I'd think conditional compilation would be a good reason, in which case naming it something like FOO_H_INCLUDED would be clearer.
I only see one very narrow use here to avoid including a header when you only need a forward declaration, but want to skip the forward declarations if the header has previously been included.
However, this is not a bottleneck in compiling C++ today, and the added confusion over either always having the forward declarations or always including the header is not worthwhile.
Even if you needed tons – and I mean hundreds to thousands of lines of these forward declarations – so that it did become worthwhile, you'd be better off with a dedicated header, similar to <iosfwd>, rather than maintaining this in multiple places.
For repurposing: unless the entire contents of the file are surrounded by the ifndef/define/endif, then FOO_H isn't really a file include guard, it's only guarding part of a file. So possibly it shouldn't be named after the whole file. Recursive inclusion of the same file is one situation where this can come up.
That said, I suspect that even so, it should be pretty obvious what the define is for (anyway, more obvious that whatever tricksy thing it is you're doing that isn't simple include guarding). Anywhere you see the pattern ifndef FOO/define FOO, or even just ifndef FOO / define lots of stuff, a simple comment can make the meaning of FOO obvious if it isn't already.
If any part of the question is whether the token FOO_H might ever be used for some other purpose: I guess if you have a file somewhere called uppercase.h which uses UPPERCASE_H as an include guard, then that could conceivably clash with someone's rot13.h, containing #define UPPERCASE_A ('N'), etc. Silly example, but if you were defining properties of letters in a header file then it's not ridiculous to think that some of them might end in _H.
More realistically, I've had projects with include files having the same basename in different directories.
So, regardless of the issue of context and repurposing, I wouldn't use FOO_H as an include guard.
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