I am new to C++. I have seen code that includes a library file (string as an example) in both the header and cpp file. Will this cause duplicate code if #ifndef is not used? or is the preprocessor smart enough to ignore it. Is it normal to include the same library in both files?
test.h
#include <string>
.
.
.
test.cpp
#include <string>
#include "test.h"
.
.
.
Is it normal to include the same library in both files?
Yes. It is normal to include a header into multiple files.
Whenever you use a declaration from a header, you should include that header. If you use std::string in test.h, then you should include <string> in test.h. If you use std::string in test.cpp, then you should in include <string> in test.cpp. Whether <string> happens to be included in one of the headers included by test.cpp is irrelevant and is something that shouldn't be relied upon.
Will this cause duplicate code if #ifndef is not used?
If a header doesn't have a header guard, then including it multiple times will indeed cause its content to be duplicated, yes.
or is the preprocessor smart enough to ignore it.
The preprocessor doesn't ignore any includes. Each include will be processed. A preprocessor may be smart enough to optimise inclusion of a header that it knows would be empty due to an include guard.
All C++ standard library header files have ifndef guards. It is safe to include them in multiple files.
The rule of thumb is to include the file everywhere where its definitions are needed. This means if you're using std::string in both h and cpp files, include <string> in both.
For any of your own header files, you should always use ifndef guards for the same purpose.
Related
In DirectX Graphics Samples MiniEngine sample, there is an "inline" source file Functions.inl that uses a macro INLINE that is defined in a header in same folder, Common.h .
What mechanism/declaration permits Functions.inl to use INLINE without an #include "Common.h" statement?
My specific issue is that I have created a VS2019 UWP C++ project, and I am importing a subset of this source and cannot compile the copy of Functions.inl without modifying and adding an #include statement.
"Math/Functions.inl" is not a source file. It is not compiled individually. It appears to be included, just like a header is. Let's take a look at how it is used:
// Core/VectorMath.h
#pragma once
#include "Math/Scalar.h"
...
#include "Math/Functions.inl"
Unlike a header, it is not included into the top of the file, but the bottom. So, I guess it could be called a footer. As you may notice, there are headers included before it. Let's take a look inside one:
// Math/Scalar.h
#pragma once
#include "Common.h"
...
Ah. So, "Common.h" is included before "Math/Functions.inl". That is why "Math/Functions.inl" can use INLINE when included into "Core/VectorMath.h".
Essentially, the file depends on a macro without including it directly and thereby it has an invisible dependency to have that header included before it.
This a bad practice in case of header files which are intended to be included by the user of the library. But this file is presumably intended to not be included except through "Core/VectorMath.h", so the the invisible dependency can even be seen as advantageous. Nevertheless, many IDEs / static code analysers will fail to analyse the file correctly, so I would personally still avoid this practice.
The *.inl extension is usually used to indicate that the file is an inline-definition of something defined in a header. Effectively, the *.inl file is generally treated as an inline-equivalent to a *.cpp file.
In the same way that *.cpp files can use symbols #included in the header for that *.cpp file, *.inl files usually have the same assumption.
In this specific example. it appears that Functions.inl is included after a bunch of other headers are included
#include "Math/Scalar.h"
#include "Math/Vector.h"
#include "Math/Quaternion.h"
#include "Math/Matrix3.h"
#include "Math/Transform.h"
#include "Math/Matrix4.h"
#include "Math/Functions.inl"
Which likely transitively pick up the INLINE macro
My question is on proper syntax and usage of header guards. For example if I am including a few common libraries in my C++ code can I make a header guard like what is shown below? Also, from the documentation I could find on header files it was suggested to put your header guard in a header file. I am using Microsoft Visual Studio. Can I just place my header guard and #include files in my main source file? Or is this a bad practice? I know you can use #pragma to function as a header guard. However, this is not a supported standard so I am trying to avoid using it.
#ifndef HEADER_GUARD
#define HEADER_GUARD
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#endif
Any help would be greatly appreciated!
You should not write the header guard in source code (.cpp) file.
We should avoid the double header guard as well The use of double include guards in C++
Header guard is to avoid multiple time inclusion of header file during compilation of code.
Also, while adding the #include file, keep in mind that we should not add the unwanted files there.
e.g.
Consider case if source file requires to #include <iostream> but you included in header file then this should be avoided. Such case #include <iostream> in source file only.
#pragma once is supported by many compilers but it's not language standard and it do not guarantee when file are referenced from remote location and different disks.
I got a comprehension issue about precompiled headers, and the usage of the #include directive.
So I got my "stdafx.h" here and include there for example vector, iostream and string. The associated "stdafx.cpp" only includes the "stdafx.h", that's clear.
So if I design my own header file that uses for example "code" that's in vector or iostream, I have to include the header file because the compiler doesn't know the declarations at that time. So why are some posts here (include stdafx.h in header or source file?) saying, it's not good to include the "stdafx.h" in other header files even if this file includes the needed declarations of e.g. vectors? So basically it wouldn't matter to include directly a vector or the precompiled header file, both do the same thing.
I know of course, that I don't have to include a header file in another header file if the associated source file includes the needed header file, because the declarations are known at that time. Well, that only works if the header file is included somewhere.
So my question is: Should I avoid including the precompiled header file in any source file and why? And I am a bit confused, because I'm reading contradictory expressions on the web that I shouldn't include anything in header files anyway, or is it O.K. to include in header files?
So what's right now?
This will be a bit of a blanket statement with intent. The typical setup for PCH in a Visual Studio project follows this general design, and is worth reviewing. That said:
Design your header files as if there is no PCH master-header.
Never build include-order dependencies in your headers that you expect the including source files will fulfill prior to your headers.
The PCH master-header notwithstanding (I'll get to that in a moment), always include your custom headers before standard headers in your source files. This makes your custom header is more likely to be properly defined and not reliant on the including source file's previous inclusion of some standard header file.
Always set up appropriate include guards or pragmas to avoid multiple inclusion. They're critical for this to work correctly.
The PCH master-header is not to be included in your header files. When designing your headers, do so with the intent that everything needed (and only that which is needed) by the header to compile is included. If an including source file needs additional includes for its implementation, it can pull them in as needed after your header.
The following is an example of how I would setup a project that uses multiple standard headers in both the .h and .cpp files.
myobject.h
#ifndef MYAPP_MYOBJECT_H
#define MYAPP_MYOBJECT_H
// we're using std::map and std::string here, so..
#include <map>
#include <string>
class MyObject
{
// some code
private:
std::map<std::string, unsigned int> mymap;
};
#endif
Note the above header should compile in whatever .cpp it is included, with or without PCH being used. On to the source file...
myobject.cpp
// apart from myobject.h, we also need some other standard stuff...
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note myobject.h does not expect you to include something it relies on. It isn't using <iostream> or <algorithm>, etc. in the header; we're using it here.
That is a typical setup with no PCH. Now we add the PCH master
Adding the PCH Master Header
So how do we set up the PCH master-header to turbo-charge this thing? For the sake of this answer, I'm only dealing with pulling in standard headers and 3rd-party library headers that will not undergo change with the project development. You're not going to be editing <map> or <iostream> (and if you are, get your head examined). Anyway...
See this answer for how a PCH is typically configured in Visual Studio. It shows how one file (usually stdafx.cpp) is responsible for generating the PCH, the rest of your source files then use said-PCH by including stdafx.h.
Decide what goes in the PCH. As a general rule, that is how your PCH should be configured. Put non-volatile stuff in there, and leave the rest for the regular source includes. We're using a number of system headers, and those are going to be our choices for our PCH master.
Ensure each source file participating in the PCH turbo-mode is including the PCH master-header first, as described in the linked answer from (1).
So, first, the PCH master header:
stdafx.h
#ifndef MYAPP_STDAFX_H
#define MYAPP_STDAFX_H
// MS has other stuff here. keep what is needed
#include <algorithm>
#include <numeric>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#endif
Finally, the source files configured to use this then do this. The minimal change needed is:
UPDATED: myobject.cpp
#include "stdafx.h" // <=== only addition
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note I said minimal. In reality, none of those standard headers need appear in the .cpp anymore, as the PCH master is pulling them in. In other words, you can do this:
UPDATED: myobject.cpp
#include "stdafx.h"
#include "myobject.h"
// code, etc...
Whether you choose to or not is up to you. I prefer to keep them. Yes, it can lengthen the preprocessor phase for the source file as it pulls in the headers, runs into the include-guards, and throws everything away until the final #endif. If your platform supports #pragma once (and VS does) that becomes a near no-op.
But make no mistake: The most important part of all of this is the header myobject.h was not changed at all, and does not include, or know about, the PCH master header. It shouldn't have to, and should not be built so it has to.
Precompiled headers are a method to shorten the build time. The idea is that the compiler could "precompile" declarations and definitions in the header and not have to parse them again.
With the speed of todays computers, the precompilation is only significant for huge projects. These are projects with a minimum of over 50k lines of code. The definition of "signification" is usually tens of minutes to build.
There are many issues surrounding Microsoft's stdafx.h. In my experience, the effort and time spent with discovering and resolving the issues, makes this feature more of a hassle for smaller project sizes. I have my build set up so most of the time, I am compiling only a few files; the files that don't change are not compiled. Thus, I don't see any huge impact or benefit to the precompiled header.
When using the precompiled header feature, every .cpp file must begin by including the stdafx.h header. If it does not, a compiler error results. So there is no point in putting the include in some header file. That header file cannot be included unless the stdafx.h has already been included first.
I have a quick question regarding header files, include statements, and good coding style. Suppose I have 2 classes with associated source and header files, and then a final source file where main() is located.
Within Foo.hpp I have the following statements:
#include <string>
#include <iostream>
#include <exception>
Now withing Bar.hpp I have the following statements:
#include "Foo.hpp"
#include <string>
And finally withing Myprogram.cpp I have the following statements:
#include "Bar.hpp"
#include <string>
#include <iostream>
#include <exception>
I know the include statements in <> in Myprogram.cpp and Bar.hpp aren't necessary for the program to compile and function, but what is the best practice or right way of doing things? Is there any reason to not explicitly include the necessary header files in each file?
You should include all necessary files in every file that needs them. If MyProgram.cpp needs string, include it, instead of relying on it being included by Bar.hpp. There's no guarantee 2 weeks from now Bar.hpp will still include it, and then you'll be left with compiler errors.
Note the necessary - i.e. make sure you actually need an include, when a forward declaration or even leaving it out completely will do.
Also, note that some system headers might include others - apart from a few exceptions, there's no requirement. So if you need both <iostream> and <string> include both, even if you can compile only with one of them.
The order in which the includes appear (system includes vs user includes) is up to the coding standard you follow - consistency is more important than the choice itself.
Include all you need in every file, but do not include any file that you do not need. Normally, it is the job of the included file to make sure it is not included twice, using precompiler flags, etc...
For example if is needed by Foo.cpp, but not by Foo.h, include it in Foo.cpp not in Foo.h. If required in both, include in both.
Tangentially, as a best practice, never use using directives in a header file. If you need you can use using directives in implementation files (.cpp).
When coding in either C or C++, where should I have the #include's?
callback.h:
#ifndef _CALLBACK_H_
#define _CALLBACK_H_
#include <sndfile.h>
#include "main.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data);
void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data);
#endif
callback.c:
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "callback.h"
#include "play.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) {
gint page;
page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook));
...
Should all includes be in either the .h or .c / .cpp, or both like I have done here?
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
void doStuffWith(FILE *f); // need the definition of FILE from stdio.h
#endif
If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.
Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.
Of course, you shouldn't be including files where you don't need to.
Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.
Also consider using forward declarations in your hpp file to further reduce the include dependency chain.
If I #include <callback.h>, I don't want to have to #include lots of other header files to get my code to compile. In callback.h you should include everything needed to compile against it. But nothing more.
Consider whether using forward declarations in your header file (such as class GtkButton;) will suffice, allowing you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).
I propose to simply include an All.h in the project that includes all the headers needed, and every other .h file calls All.h and every .c/.cpp file only includes its own header.