In this example code, I have 3 files:
testHeader.h:
void hello() { }
file1.h:
#include "testHeader.h"
#include <iostream>
void sayHi() { std::cout << "hi" << std::endl; }
file2.h:
#include "file1.h"
void sayHello() { std::cout << "hello" << std::endl; }
If file1.h includes testHeader.h and file2.h includes file1.h, do testHeader.h and its functions become accessible in file2.h? What about <iostream> and its functions?
Unless protected by preprocessor guards in weird ways, yes, you get them all. #include is largely a preprocessor trick, roughly equivalent to dumping the text of the include into the source code, and it's transitive; if you #include <a.h>, you get the expanded form of a.h, including the preprocessor expanded form of all its includes, all their includes, etc., etc. ad infinitum, in a single pass.
Note that it's still a good idea to explicitly include all the things you rely on directly; sure, the other .h files might #include <vector> today, but that's no guarantee the next release will have them if they're not a necessary part of the API being exposed.
It's also worth noting that preprocessor include guards (and/or #pragma once) is used almost universally to mean a .h file's contents don't get included twice (by convention, not a guarantee; in the case of poorly written .h files, or weird ones designed for multiple inclusion with different preprocessor setups it won't be obeyed); there is little to no cost to re-including a header in the .cpp that it already got from a .h you included. On older compilers, without #pragma once and with no special handling for include guards, it might have to load the header a second time, see the guard, and dump nothing on the second include; many newer compilers are smart enough to avoid even that cost. Point is, don't try to optimize by avoiding redundant #includes; every file should have the complete set of #includes needed for the things used in that file, no more, no less.
If you work on older compilers, without #pragma once, then try to do as following.
--- file1.h ---
#ifndef FILE1_H
#define FILE1_H
#include "testHeader.h"
#include <iostream>
void sayHi();
#endif
--- file1.cpp ---
#include "file.h"
void sayHi() { std::cout << "hi" << std::endl; }
--- file2.h ---
#ifndef FILE2_H
#define FILE2_H
#include "file1.h"
#include <iostream>
void sayHello();
#endif
You shouldn't make a body of function in HEADER file. It might cause a compile error for multiple links for the same function. Please write function' prototype and body into Header and Source file seperately.
Related
I want to run a small simulation in c++.
To keep everything nice and readable I seperate each thing (like all the sdl stuff, all the main sim stuff, ...) into it's own .h file.
I have some variables that I want all files to know, but when I #include them in more then one file other the g++ compliler sees it as a redefinition.
I understand why he does this, but this still leaves me with my wish to have one file where all important variables and constants for each run are defined and known to all other files, to easily find and change them when running my simulation.
So my Question here: Is there a good workaround to achieve that or something similar?
You can put the declarations for all the globals in a header and then define them in a source file and then you will be able to use those global variables in any other source file by just including the header as shown below:
header.h
#ifndef MYHEADER_H
#define MYHEADER_H
//declaration for all the global variables
extern int i;
extern double p;
#endif
source.cpp
#include "header.h"
//definitions for all the globals declared inside header.h
int i = 0;
double p = 34;
main.cpp
#include <iostream>
#include "header.h" //include the header to use globals
int main()
{
std::cout << i <<std::endl;//prints 0
std::cout<< p << std::endl;//prints 34
return 0;
}
Working demo
Mark them as extern in the header and have one translation unit that defines them.
Note: Without LTO (link time optimization) this will seriously slow down your simulation.
So I am just wondering if you #include something in a for example header.h file:
For example this is called header.h:
#include <vector>
#include <iostream>
#include <somethingElse>
So if for example I make a file called something.cpp Do I need to put all those include statements again?
#include "header.h"
// If I include #header.h in this file. Do the #include carry over to this file. Or do they not
I am wondering because whenever I include <vector> something in my .h file the #include statements that I used previously in the .h file always turn grey which means they are not used. Is it because I used it in the .h file? Its not a problem or anything I am just curious.
You don't need to include those headers again because your compiler can find those headers. You can also try to read and understand the makefile (or CMakeList) which will help.
Try always to avoid "Multiple file inclusion" via using inclusion guard or #pragma once in order to prevent the multiple file inclusion.
To include file means that the content of the file will be added to the very place you wrote include.
Here's an example:
// header.h
const int vlaue = 10;
const int value2 = 0;
// main.cpp
#include "header.h"
#include "header.h"
Above the content of "header.h" is added twice to main.cpp.
Do you know what is the result? It's a compile-time error complaining of redefinition of value and value2.
In the above example I think green programmers don't get trapped by it but it is just an explanation, So what I talk about is when a huge program where many header files and many source files and some files include others then it'll be so difficult to track the right file inclusion.
The workaround that is to use inclusion guards or pragma once eg:
Let's modify our header.h to look like:
// header.h
#ifndef MY_HEADER_H
#define MY_HEADER_H
const int vlaue = 10;
const int value2 = 0;
#endif
Now in main.cpp:
#include "header.h"
#include "header.h"
#include "header.h"
The code above works fine and no duplicate of header content is added to main.cpp. Do you know why? It's the magic of Macro there. So at first time the pre-processor checks whether a macro has been already defined with the name MY_HEADER_H or not and for sure for the first time it is not defined so the content is added. The second and so on the condition fails because the macro is already defined thus the content of header.h will not be added to where it is called.
The draw back of inclusion guard is if you have a macro with same name as the inclusion guard thus it is already defined so the content will never be added (empty content). Thus you get a compile-time error:
value, `value2` undeclared identifiers.
The second solution is using pragma eg:
Let's modify our header.h file:
// header.h
#pragma once
const int vlaue = 10;
const int value2 = 0;
// main.cpp
#include "header.h"
#include "header.h"
The code above works correctly so no multiple inclusion of header.h That is because of the magic of pragma once: which is a non-standard but widely supported pre-processor directive designed to cause the current source file to be included only once in a single compilation. Thus, #pragma once serves the same purpose as include guards, but with several advantages, including: less code, avoidance of name clashes, and sometimes improvement in compilation speed.
Finally you should include header wherever their content is used eg:
// Shape.h
class Shape{
// some code here
};
// Cube.h
#include "Shape.h"
class Cube : public Shape{
// some code here
};
// Cuboid.h
// #include "Shape.h"
#include "Cube.h" // So here the Shape.h is added to Cube.h and Cube.h is added here.
class Cuboid : public Cube{
// some code here
};
As you can see above the content of Shape.h is added to Cuboid.h indirectly because it is added to Cube.h and cuboid.h includes Cube.h so it is added to it. So without inclusion guards or pragma once if you include the two headers in one source file you get duplicate content there.
I have frequently seen people #include "foo.h" at the top of "foo.cpp". It looks like you could always do this, but people don't. So there must be some reason behind the choice.
When should I #include the header (foo.h) inside the source file (foo.cpp)?
The reason to put it at the top is simply to check that its contents don't depend on any other headers. For example:
// foo.h
void f(std::vector<int>& v);
// foo.cpp
#include <vector>
#include "foo.h"
// foo1.cpp
#include "foo.h"
#include <vector>
In foo.cpp, there's no problem: everything compiles just fine. foo1.cpp, on the other hand, won't compile, because foo.h uses std::vector without an include directive.
Having every header file compilable on its own avoids mysterious failures that otherwise occur when you change include directives in a file that has nothing to do with foo.cpp. These are sometimes hard to identify, and they're always frustrating.
You need to include the header if you're using anything inside the header.
For example, if you need to create foo someObject = new foo(); in your main method, you need to include the header foo.hthat has that class definition.
You only need to include things that you know you're going to use.
You can include a header file whenever you want.
Anyway, suppose you have a file main.h similar to the following one:
#ifndef FOO_H
#define FOO_H
struct S { };
#endif
Now, this main.cpp works just fine, as you mentioned:
void f() { }
#include "foo.h"
int main() { f(); }
Anyway, if I slightly change the main.cpp it doesn't work anymore:
void f() { S s{}; }
#include "foo.h"
int main() { f(); }
The problem is that S is declared after its first use and it is not visible when the definition of f is encountered for the first time.
So, the rule of thumb could be - include a header immediately before you start using something (let me say) imported by that file.
Anyway, this could quickly lead to messy files with #include directives spread all around and a common practice is to simply put all of them at the top of the file and that's all.
I'm creating an header-only C++11/14 library and I'm not sure on how I should handle #include directives between library files.
Should I try to group as many #include directives as possible in the user-oriented module header file or should internal files include files they require (sometimes repeating the same includes)?
Approach A:
In this approach, the module header file includes all required dependencies and then includes the implementations. The implementations' header files do not include anything by themselves.
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
-
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
-
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
-
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
Approach B:
In this approach, the module header file includes only the implementation headers. If the implementation headers require additional includes, they include the files themselves (recursively), sometimes repeating the same include.
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
-
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
-
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
-
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
What is the best approach?
Intuitively, I think Approach A is the best, as it avoids repeating the same includes and makes clear what files need to be included before the other files. The biggest drawback is, though, that syntax highlighting stops working in my IDE (QT-Creator), in the implementation files with no include directives.
EDIT:
This question was voted to be closed for the reason "opinion based". I disagree, because in a large header-only project such as my library including files may take a lot of compile time. Therefore, approach A may be faster than approach B, or the opposite.
Approach B is actually the best approach, since including the same header multiple times does not produce any observable compilation time increase, but is advantageous for the following reasons:
Modern IDEs can use libclang or proprietary solutions to parse the #include directives and provide code-aware syntax highlighting and autocompletion features.
As mentioned by TemplateRex, it becomes much easier to verify a sane build process. CMake, for example, provides macros that automatically generate a test for every header.
As mentioned by Alf, it is good practice to have every file include all the headers it depends on - users of the library can then "cherry-pick" header files they require, instead of being unexpectedly force to manually include a parent header.
#include "DLLDefines.h"
#include "DLLDefines.h"
The above actually passed compilation, but why?
Well, it's legal because it has to be legal. Because you often include the same header multiple times without even realizing it.
You might include two headers in a .cpp file, each of which include a number of files, some of which might be included by both.
For example, all the standard library headers (say, string or vector for example) are probably included in most of your headers. So you quickly end up with the same header being indirectly included multiple times in the same .cpp file.
So in short, it has to work, or all C++ code would fall apart.
As for how it works, usually through include guards. Remember that #include just performs a simple copy/paste: it inserts the contents of the header file at the #include site.
So let's say you have a header file header.h with the following contents:
class MyClass {};
now let's create a cpp file which includes it twice:
#include "header.h"
#include "header.h"
the preprocessor expands this to:
class MyClass {};
class MyClass {};
which obviously causes an error: the same class is defined twice. So that doesn't work. Instead, let's modify the header to contain include guards:
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
Now, if we include it twice, we get this:
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
And this is what happens when the preprocessor processes it:
#ifndef HEADER_H // HEADER_H is not defined, so we enter the "if" block
#define HEADER_H // HEADER_H is now defined
class MyClass {};// MyClass is now defined
#endif // leaving the "if" block
#ifndef HEADER_H // HEADER_H *is* defined, so we do *not* enter the "if" block
//#define HEADER_H
//
//class MyClass {};
//
#endif // end of the skipped "if" block
So, the end result is that MyClass got defined only once, even though the header was included twice. And so the resulting code is valid.
This is an important property of header files. Always define your headers so that it is valid to include them multiple times.
It depends on the header file; there is no language restriction on multiple includes of the same file.
Some files are designed to be included multiple times (e.g. <assert.h> can be included multiple times to turn 'on' and 'off' assert).
Many files are safe to be included multiple times because they have include guards, others are not and should be included only once in a translation unit or even a program.
include has nothing to do with the C or C++ language. It is a directive to the preprocessor to bring in a file. The preprocessor doesn't care what file is brought in and it shouldn't. It might be perfectly acceptable to do this:
void Foo::SomeFunc(int cond)
{
switch (cond) {
case kThisCase:
#include "longFirstCase.h"
break;
case kSecondCase:
#include "longSecondCase.h"
break;
case kThirdCase:
#include "longFirstCase.h"
#include "longSecondCase.h"
break;
}
}
I have seen the same file included several times as a configuration mechanism as well.
Granted, there are a number of ways to factor that example that are better, but the point is that there may be perfectly good reasons why you would want to and therefore no restriction on the use.
Probably you have some #define in DLLDefines.h around your code that prevents it from being included twice.
#ifndef DLLDEFINES_H
#define DLLDEFINES_H
// your code
#endif
As long as the multiple inclusion of header files do not violate ODR (One definition Rule) $3.2, the code is well-formed.
It's called an include guard.
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct foo {
int member;
};
#endif
Quote from Wikipedia:
In the C and C++ programming languages, an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the #include directive. The addition of #include guards to a header file is one way to make that file idempotent.
See link above for more information.
DLLDefines.h may also have #pragma once at the
top, #pragma once ensures that file gets included only once.