Purpose of Header guards - c++

In C++ what is the purpose of header guard in C++ program.
From net i found that is for preventing including files again and again but how do header guard guarantee this.

The guard header (or more conventionally "include guard") is to prevent problems if header file is included more than once; e.g.
#ifndef MARKER
#define MARKER
// declarations
#endif
The first time this file is #include-ed, the MARKER preprocessor symbol will be undefined, so the preprocessor will define the symbol, and the following declarations will included in the source code seen by the compiler. On subsequent #include's, the MARKER symbol will be defined, and hence everything within the #ifnde / #endif will be removed by the preprocessor.
For this to work properly, the MARKER symbol needs to be different for each header file that might possibly be #include-ed.
The reason this kind of thing is necessary is that it is illegal in C / C++ to define a type or function with the same name more than once in a compilation unit. The guard allows you to #include a header file without worrying if has already been included. Without the guard, multiple inclusions of the same header file would lead to unwanted redeclarations and compilation errors. This is particularly helpful when header files need to #include other header files.
In short, it doesn't prevent you from #include-ing a file again and again. Rather, it allows you to do this without causing compilation errors.

The purpose of header guards is to prevent issues where some code may appear only once per translation unit.
One example is a struct. You cannot redefine a struct even if the second definition is identical. So, if you try to compile the following:
struct foo { int x; };
struct foo { int x; };
The compiler will fail because of the redefinition.
It can be hard to guarantee you only include a header one time (this happens when headers include other headers). If your header has struct definition, this will cause the compile to fail. Header guards are the easy trick so that even if a header is included multiple times, it's contents only appear a single time.

Related

Need help in understanding concept: why declare a function in header but define it in source file?

(My apology if this question sounds familiar, but I was really confused. And I could not comment under existing questions. )
I browsed a few questions, this, whose answer says:
If ...(defined a function in header), and then include the header into two or more different source files, you'll have multiple definitions of the same function.
But I thought the book taught us to always wrote definition guard inside headers. With the guard, we won't have multiple definitions, right?
I tried to find the reason in book , but with not much help: it says the reason (why function is declared in header file, and defined in source file) is the same reason as variables (in a previous chapter). And when I jump to that previous chapter, there is no explicit explanation.
why declare a function in header but define it in source file?
The declaration is needed to call the function. It goes in the header so that any file which wants to call the function can include the header and have the declaration available.
There can only be one definition, so it goes in just one source file.
With the guard, we won't have multiple definitions, right?
There would be one definition in each source file that included the header. The guard prevents multiple inclusions from the same source file, but not inclusions from different source files.
But I thought the book taught us to always wrote definition guard inside headers.
Definition guard prevents a header to be included multiple times in one C file. It does not prevent a header from being included in multiple C files.
With the guard, we won't have multiple definitions, right?
If you put the definition in a header, and include that header in multiple C files, then you would end up with multiple definitions of the same function.
Having multiple definitions of a function or a variable will cause an error at linkage time, unless the function or the variable is static. In case of a static function / variable you would end up with multiple copies of that function / variable, which is not usually the desired outcome.
With the guard, we won't have multiple definitions, right?
Not right. Include guards ensure that when a source file is compiled, the header won't be processed twice. But when you have several source files, each file is compiled separately, so include guards do not stop multiple definitions.
That's not the same thing, using a definition guard doesn't prevent one implementation from spanning multiple source files, it prevents the same declaration from being included more than once in the same file (which would cause compilation errors indeed).
So a guard is useless against a function defined directly in the header, since its implementation will be then included in multiple source files and, unless the compiler chooses to inline it, it will be present more than once. Placing the implementation in the source file will make the function being compiled in its own translation unit, and any call to it will be resolved accordingly.
Actually the compiler could inline even functions implemented in the source file so this could not happen.
A declaration goes in the header.
A definition goes in the body.
The header guard is to prevent multiple declarations at compile time, while compiling a single unit that may include the same header more than once (via other The definition goes in the body to prevent multiple compiled versions of the definition in multiple objects that included it colliding at link time.
Edit to answer comment because I can't format a comment:
It's not OK to define the same thing twice.
It is not OK to declare the same thing twice.
It is OK to pre-declare the same thing twice.
// predeclare:
class thingy;
// declare:
class thingy { int x(); };
// define:
thingy::x() { return 1; }
Anything you put in a header is likely to appear twice when compiling a single file because headers often get included by other headers, so they get included more than once. Header guards prevent this at compile time.
Anything you put in a header which defines something is likely to end up being defined in the compilation of more than one file if they both include the header, and then appear twice at link time. Header guards cannot prevent this, hence we avoid defining things in headers.
You can think of the #include in C++ as a giant macro - it means "grab an entire file and shove it into my source code at this point, before you compile it".

Adding more code makes code uncompileable

I have a header file which begins with
#if !defined(__GLOBAL_H)
#define __GLOBAL_H
then some code followed by
#endif
The code contains only function declarations, some include of other header files and the a few template functions. However, the problem occurs when I add one single line of code. I get linker error that the function I added has already been defined in an object file. I'm using Visual Studio 2012 Premium as compiler. I have tried to remove any existing function from the header file, and that also goes through the compiler. On the other hand, if I add any new line that may be new to the compiler, it refuses to compile saying it has already been defined. Does anyone have any clue what might be wrong or can I have stumbled upon an error inside the compiler itself? (which I highly doubt)
Edit:
The solution was to declare the function the the header file, but to define it in the CPP file. But the real issue was that when I include a header file for returning an object of the type declared in the header file, it does not compile. It many of the errors "Missing ; in front of *" which was types declared in other header files.
Although you haven't shown use any code or error messages, I'm guessing that there are function definitions (including the code for the function body), not just declarations, in the header.
These must either be declared inline, which allows them to be defined in more than one translation unit; or moved into a single source file, leaving just the declaration in the header, so they are only defined on one translation unit.
The "One Definition Rule" says that (unless they are inline) functions may only have one definition in the program.
Also, your include guard shouldn't begin with an underscore, nor contain a double underscore; names like that are reserved.
Adding non-inlined function definitions to header files is generally bad. The compiler will generate code for the function in every file it is included in resulting in the redefintion error you are encountering. Instead you should declare the function in the header and place the definition in a source file (.cpp).
Global.h
#if !defined(__GLOBAL_H)
#define __GLOBAL_H
void somefunction(); // <-- declaring the function.
#endif
SomeSource.cpp
#include "Global.h"
// Here is where define the function
void somefunction()
{
}

function defintion in header file in C++

I have C++ project which consists of multiple (in fact many) .cpp and .h files. While writing header files i have a file as follows
For eg MyHeaderFile.h
#ifndef _MYHEARDERFILE_H
#define _MYHEARDERFILE_H
// Here i have function defintion.
void myFunc() {cout << "my function" << endl; }
#endif
Above file is included in multiple files. While compiling i have getting "multiple definition of "myfunc" error.
I am expecting the header is included only once as i have #ifndef check so i am expecting error should not be thrown.
For example in case of templates we have to define in header file, in this case how we can avoid the problem i am facing now?
Can any one please help me why i am seeing the error? is my understanding right?
Thanks!
Normally, one puts function declarations in header files, and function definitions (i.e. the actual function body/implementation) in source files. Otherwise, you get exactly the issue you're seeing: the header file is #included (i.e. substituted) into multiple source files, so the function ends up being defined multiple times. This confuses the linker, so it complains.
The header-guard #ifndef ... stuff only prevents a header from being substituted into the same source file multiple times. Remember that each source file is compiled completely independently from all the others; all #defines and other definitions are "reset" for each one.
One possible alternative solution is to leave the function definition in the header file, but simply to mark it inline (this has the side-effect of eliminating the linker error). But, personally, I wouldn't do that.
Every function must be defined only once in a single translation unit (this is called One definition rule, and applies not only to functions). By placing the definition in a header which is then included, you are violating this rule.
You can simply leave the declaration
void myFunc();
in the header, and define myFunc in a .cpp which provides the definition.
Otherwise you can declare your function inline.
Note that when using templates, instead, you are usually led (for template-related specific issues) to place definitions directly in the headers, which could appear surprising given the problems you are facing now.

Should you include source code in a header file?

I am working on porting some source code to a linux system, and as expected, some stuff is broken. One thing that is throwing an error for me right now, is that someone has a .h and a .cpp file that both use fclose()
The compiler is complaining about fclose() being undeclared in the header file.
here was the function declaration in the header file:
void closeFile() { if (fp) fclose(fp); }
Now, I think this is bad style, but also - how did they get this working before? Did their version of the compiler allow this kind of behavior?
Should I fix this by including stdio in the header, or move the whole thing to the cpp?
It's not bad style, you can put source code in header files, and some times you're forced to, in particular:
When defining a template class/function.
When defining an inline function.
Anyway you shouldn't put a free (defined outside a class scope) non-inline function in a header file, since that would be compiled any time a source file include such header (and this will give you a linking error).
If you're getting an error that states fclose hasn't been declared, it's probably because cstdio (or stdio.h) wasn't declared before that piece of code. Put an #include <cstdio> at the beginning of the header file.
Just to add 2 things about the other answers, remember inline is not an order, is more a guess of what the compiler should do, unless you force inline. Most compilers can decide when to inline a function, even if you did not declare it inline. It's not a must, it is a should.
Sometimes you really need to include such function/structs/classes definitions in the header, and sometimes they are not trivial or that simple. But those definitions are usually some auxiliar functions you need and you just don't want to include them on the main file, just to organize things better.
The best examples I ever seen (ok, and I didn't see those many) about this practice is game source code (that's my main interest :) ).
By the way, I usually do not put any declaration on header files (except structs and enums), I put them on separated files, unless if:
There are only a few declarations/aux functions to be made; or
These declarations are functions that I will use in another contex (of the same project, in the case) and I just think it's better to treat them as a separated 'auxiliar library' (within the same context).
Hope it helps somewhat.
Keep in mind that header files aren't compiled by themselves (usually). They are #included into source files and the definitions available when the header file is parsed are whatever was included in the source file above the header file in question.
Regardless of whether the header file is an appropriate place for the implementation of closeFile(), your header file should #include everything it needs at the top of itself. So, add #include <stdio.h> at the top of the header file.
(Note that if this is code intended to be compiled into the Linux kernel itself, you may need a different header than stdio.h. Often application-level headers aren't suitable to be used in the kernel sources.)
fclose() will be undefined if you haven't included stdio.h either in this header or before it everywhere this header is used. That is why the error occurs.
I personally see nothing wrong with the code being allowed to be in a header file, however, if it is, and you're using C99, you should declare it
inline void closeFile() { if (fp) fclose(fp); }
This means multiple compiled objects won't have closeFile() symbols (because of inline) and the inline hints to the compiler that this shouldn't be left as a function call but substituted inline which is probably want you want for speed.
The headers are included by textual substitutions (that is the whole content of the header is substituted to the #include declaration). So if there is only one .cpp file that include this particular header, this is equivalent with having the function defined in the .cpp file. I think this is the reason why it was working (at link time).
The C standard only define the header that must be included to have a function available but does not forbid the system header to include one another. So it is possible that on some system, the stdio.h header was implicitly included by another header (and thus no error reported by the compiler).
Personally, I would move such code to the .cpp file, as it will be less brittle (the header can be included by multiple .cpp files, the header will not require a previous inclusion of the stdio.h header) and will allow for quicker recompilation if the implementation must be changed (to add logging or proper error handling, as closing a file can fail).

Preprocessor directive #ifndef for C/C++ code

In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...