C++ mass-#include - c++

I always need to write #include "headername.h" when including another class. Is it possible to acess other classes without writing it or including more than 1 class with a "#include"?

What the #include directive does is exactly what its name implies, it literally includes the contents of the wanted file into the source. It's done at an early step in the compilation process, before the actual compiler gets the source. The source with all its headers files is called translation unit, and it's on this translation unit that the compiler works on.
As for why you need the header files, remember that C++ needs everything to be declared or defined before it's being used. If the compiler doesn't know there is a class named Foo you can't declare variables of type Foo. If you don't #include the header file there Foo is defined, the compiler simply will not know there is such a class.
If you end up having to include many headers in many source files, you can put the common headers in another header file, whose only purpose is to include other header file. For example, if you in many source file includes <string>, <vector> and <iostream>, then you create a file called headers.h containing
#ifndef HEADERS_H__
#define HEADERS_H__
#include <iostream>
#include <string>
#include <vector>
#endif // HEADERS_H__
Then you can include this file in your source files instead:
#include "headers.h"

You can create your own header file which includes the necessary includes and then include this header file.

Related

How to include libraries in Visual Studio automatically?

ALWAYS when I start a new class (EX: main.cpp) I need to
#include <iostream>
#include <string>
#include <math.h>
There is a way to make it automatically ? I mean every time when I create a new class they will already be included ?
A cpp file is not a class, it's a source file. A cpp file may include a class, or multiple classes, or no classes. Similar, a header filer is not a librarie, it's just a header file.
Add your includes to a header (.h file), and then your cpp file only has to include that single header to include all those common includes. Visual Studio even has something called a precompiled header, which is exactly meant as such a header with common includes, except that it's precompiled (which means, using that will compile faster than using a regular header). Afaik, you'll still have to include that single header yourself, tho, so you won't get around writing at least one #include ...
My solution is more a workaround than a "real" solution but : You need these lines at least once in your program.
So I'd create a headers_container.hpp file containing stuff my whole program needs, like these #include.
For example :
headers_container.hpp :
#include <iostream>
#include <string>
#include <math.h>
// Some stuff my whole program needs...
in your *.cpp files :
#include "headers_container.cpp"
// Your compiler knows iostream, std::strings and math now
Make sure the path to headers_container.hpp is correct (if the .hpp is not in the same folder as your .cpp
Using this method, you can add one #include in headers_container.hpp and it will update all the .cpp files.
Moreover you can write a small script to generate files (I did the script you can find here : https://gitlab.com/-/snippets/2033889 )
Enjoy your way in programming ! :)

C++ Using MACRO without INCLUDE statement

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

Header files and include best practice

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).

#include in .h or .c / .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.

Is there a standard #include convention for C++?

This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.
Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?
For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.
Some best practices:
Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers
Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers
Every header is wrapped with:
#ifndef HEADER_XXX_INCLUDED
#define HEADER_XXX_INCLUDED
...
#endif /* HEADER_XXX_INCLUDED */
Headers do not include each others in cycles
Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included first by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc.
These are not necessarily "best practice", but rules which I usually follow also:
Project-specific headers are included as #include "..." and before the system-wide headers, which are included as #include <...>
Project-specific headers are included in alphabetical order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents and the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.
Check out John Lakos's Large-Scale C++ Software Design. Here's what I follow (written as an example):
Interface
// foo.h
// 1) standard include guards. DO NOT prefix with underscores.
#ifndef PROJECT_FOO_H
#define PROJECT_FOO_H
// 2) include all dependencies necessary for compilation
#include <vector>
// 3) prefer forward declaration to #include
class Bar;
class Baz;
#include <iosfwd> // this STL way to forward-declare istream, ostream
class Foo { ... };
#endif
Implementation
// foo.cxx
// 1) precompiled header, if your build environment supports it
#include "stdafx.h"
// 2) always include your own header file first
#include "foo.h"
// 3) include other project-local dependencies
#include "bar.h"
#include "baz.h"
// 4) include third-party dependencies
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
Precompiled Header
// stdafx.h
// 1) make this easy to disable, for testing
#ifdef USE_PCH
// 2) include all third-party dendencies. Do not reference any project-local headers.
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iosfwd>
#include <iostream>
#include <vector>
#endif
I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;
class Bar
{
Foo * m_foo;
};
Bar.cpp:
#include "Foo.h"
#include "Bar.h"
Use only the minimum amount of includes needed. Useless including slows down compiling.
Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:
class BogoFactory;
edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:
a.h
#include "b.h"
b.h
#include "c.h"
If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.
There are several problems with the #include model used in C/C++, the main one being that it doesn't express the actual dependency graph. Instead it just concatenates a bunch of definitions in a certain order, often resulting in definitions coming in a different order in each source file.
In general, the include file hierarchy of your software is something you need to know in the same way as you know your datastructures; you have to know which files are included from where. Read your source code, know which files are high up in the hierarchy so you can avoid accidentally adding an include so that it will be included "from everywhere". Think hard when you add a new include: do I really need to include this here? What other files will be drawn in when I do this?
Two conventions (apart from those already mentioned) which can help out:
One class == one source file + one header file, consistently named. Class A goes in A.cpp and A.h. Code templates and snippets are good here to reduce the amount of typing needed to declare each class in a separate file.
Use the Impl-pattern to avoid exposing internal members in a header file. The impl pattern means putting all internal members in a struct defined in the .cpp file, and just have a private pointer with a forward declaration in the class. This means that the header file will only need to include those headerfiles needed for its public interface, and any definitions needed for its internal members will be kept out of the headerfile.
Building on what antti.huima said:
Let's say you have classes A, B, and C. A depends on (includes) B, and both A and B depend on C. One day you discover you no longer need to include C in A, because B does it for you, and so you remove that #include statement.
Now what happens if at some point in the future you update B to no longer use C? All of a sudden A is broken for no good reason.
In A.cpp, always include A.h first, to ensure that A.h has no additional dependencies.
Include all local (same module) files before all project files before all system files, again to ensure that nothing depends on pre-included system files.
Use forward declarations as much as possible.
Use #indef/#define/#endif pattern
If a header is included in A.h, you don't need to include it in A.cpp. Any other headers A.cpp needs must be explicitly included, even if they happen to be provided by other .h files.
Organizing code files in C and C++: