When to include foo.h in foo.cpp - c++

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.

Related

Does C++ include all headers a included header file includes?

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.

If you include something in the .h file Do you have to include the same thing again?

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.

Arduino library: multiple definitions of a function

Today I encountered a weird problem when trying to use IRremote library, and I managed to strip down the problem as following. If you have a folder in libraries, with Foo.h and Foo.cpp inside, and write a sketch to include Foo.h:
Foo.h
#ifndef Foo_H
#define Foo_H
int AAA() {
return 0;
}
#endif
Foo.cpp
#include "Foo.h"
Sketch
#include <Foo.h>
void setup(){
}
void loop(){
}
The error message is:
Foo\Foo.cpp.o: In function `AAA()':
E:\workShop\Arduino\libraries\Foo\/Foo.h:5: multiple definition of `AAA()'
includeTest.cpp.o:E:\workShop\Arduino\libraries\Foo/Foo.h:5:
first defined here
I'm using a Windows 7 32-bit machine. Tested on Arduino 1.0.5, 1.0.4, and 21, 22.
So with some research I figured out the problem comes from my confusion of preprocessor and linking. This question explains how preprocessor includes file and include guard:
In C++ why have header files and cpp files?
These are some of the pages helped me understand linking:
1.8 — Programs with multiple files
GCC and Make - A Tutorial on how to compile, link and build C/C++ applications
Guide: Multiple sources
And this is a better explanation of inline specifier:
inline specifier
Well, you have defined the function in two places: once in Foo.cpp where it includes the header, and again in your sketch where it includes the header. C and C++ headers don't provide a module system, they're just literally pasted in place of the include statement.
Either declare AAA in the header, but define it in Foo.cpp (so there's only one definition), or mark it inline.
Well, the distribution of stuff in your files is more than unusual to say the least.
Here is how it is commonly done:
Foo.h
#ifndef Foo_H
#define Foo_H
int AAA(void); // Just the prototype, not the function body
#endif
Foo.cpp
#include "Foo.h" // include the h file, although not strictly neecessary
// make the function and body
int AAA(void)
{
return 0;
}
Sketch.cpp
#include <Foo.h> // include prototype, so the AAA function becomes known
void setup()
{
...
AAA(); // call AAA somewhere
}
void loop(){
}
You define the function in the header, so you should use the inline keyword:
inline int AAA(){return 0;}
// ^^^^^^^^^^ definition
Alternatively, place only the declaration in the header, and the definition in an implementation .cpp file, to be compiled.
Foo.h
#ifndef Foo_H
#define Foo_H
int AAA();
#endif
Foo.cpp
#include "Foo.h"
int AAA(){return 0;}
It is a little more complicated than Bbrado's answer if the structure of your program is a little more complicated. You need to #include <Arduino.h> and #include the help file as shown here:
testCall.ino
#include "testCall.h"
void setup() {
AAA();
}
void loop() {
}
testCall.cpp
#include "testCall.h"
beeHive AAA(void){
beeHive a;
a.bee = (byte)1;
a.hive = (byte) 2;
return a;
}
testCall.h
#include <Arduino.h>
struct beeHive {
byte bee;
byte hive;
};
beeHive AAA (void); // prototype only

Template Linking and Separation of .h and .cc Files

I've been doing some reading into designing template code have a question about it. Most of the solutions to problems relating to designing code as templates seem to either be:
Put definitions of prototypes into the header file
Use the export keyword like this (which requires an extra compiler option)
Specifically lay out how the templates will be used in the .cc/.cpp file.
For example:
// File: foo_impl.cc
// We're working with Class Foo
#include "foo.cc"
template class Foo <int>;
template class Foo <string>;
// etc.
None of these methods seem very effective. Unless if I'm missing something, they don't seem to offer the ability for a user to simply import the header file and link the template code (in a .cc file) without doing extra work. I was wondering if people could take a look at what I'm doing with my own code and tell me if these violate some kind of best practices protocol or if they could cause an issue that I'm just not seeing. Here's what I've been doing...
In main.cc:
#include <iostream>
#include "foo.h"
using namespace std;
int main (void) {
Foo <string> f ("hello world");
string s = f.get ();
cout << s << endl;
return 0;
}
In foo.h:
#ifndef FOO_H
#define FOO_H
template <class T>
class Foo {
public:
Foo (T);
T get ();
private:
T data;
};
#endif
#include "foo.cc"
In foo.cc:
#ifndef FOO_CC
#define FOO_CC
#include "foo.h"
template <class T>
Foo :: Foo (T stuff) {
data = stuff;
}
template <class T>
T Foo <T> :: get () {
return data;
}
#endif
I've been able to compile the code with all warnings in gcc 4.1.2. Thank you!
I personally prefer to put the declaration (.h) in a separate file from the definition (your .cc file). Also, I'd avoid including the .cc file in the .h file. Methods in a .h file should only be inline methods.
Let's say in your example you also had a header file (bar.h) that simply declares a class that has a Foo data member.
Every time you would modify the definition of the Foo class, you would cause a recompile of anyone who includes bar.h, even tough they couldn't care less about the definition of Foo. However, bar.cpp is probably where you actually implement stuff and that file DOES need to include the implementation of your template. This seem trivial in small projects, but becomes a source of headaches in big projects that constantly recompile files for no reason. I've seen people throwing SSDs and Incredibuild at stuff that could be fixed by simple forward declares and better header management.
Personally, I use .imp.h for the implementation of my templates. Including cc files or cpp files seems yucky to me.
For example ( sorry for compilation errors. ;) )
// foo.h
#ifndef foo_h
#define foo_h
template< typename T >
struct Foo
{
Foo( T value );
void print();
T _value;
};
#endif
//foo.imp.h
#ifndef foo_imp_h
#define foo_imp_h
#include "foo.h"
#include <iostream>
template< typename T >
Foo< T >::Foo( T value ) : _value( value ) {}
void Foo< T >::print() { std::cout << _value << std::endl; }
#endif
// bar.h
#ifndef bar_h
#define bar_h
#include "foo.h"
struct Bar {
Foo< int > _intFoo;
Foo< double > _doubleFoo;
void print();
};
#endif
// bar.cpp
#include "bar.h"
#include "foo.imp.h"
void Bar::print()
{
_intFoo.print();
_doubleFoo.print();
}
// foobar.cpp
#include "bar.h"
void foobar()
{
Bar bar;
bar.print();
}
Had the defintion of foo be included in or by foo.h, bar.cpp and foobar.cpp would have been recompiled. Since only bar.cpp is concerned with Foo's implementation, splitting the defintion and declaration of Foo in two files and not having foo.h include foo.imp.h at the end saved me a recompile of foobar.cpp.
This is something that happens all the time in projects and can be very easily avoided by following the .h/.imp.h rule I explained above. The reason you never see this in stuff like STL or boost is because you are not modifying those files. It doesn't matter if they are in one or two files. But in your own projects, you will be constantly modifying the definitions of your templates and this is how you reduce recompilation times.
If you already know beforehand which types are actually going to be used with your template, than do not even bother with the .imp.h file. Put everything in a .cpp and do this at the end
// foo.cpp
// Implementation goes here.
// You might need to put something in front so that it gets exported from your DLL,
// depening on the platform
template class foo< int >;
template class foo< double >;
Lets start with basic ideology of .h and .cc files. When building libraries, the idea is to share only your header files and not your implementation (mean .cc files). This is also the basics OOP's encapsulation, abstraction etc, to hide the implementation details.
Now templates in C++ violates this principle, bcoz C++ is a compiled language. And compiler generates all the needed code during compilation. Now to adhere to OOP we end up with fragile templates which not 100% generic in nature.
Keep declaration and definitions separate (SHARING implementation)
If you are just want to keep things clean and in order, then you can include your implementation file in another header. I think it should be header file as this goes with basic convention that we share .h files and we keep .cc files not to be shared (until you are sharing the code itself). Here is how the files look.
foo.h
This is simple file with including foo_impl.h.
#ifndef FOO_H
#define FOO_H
template <class T>
class Foo {
public:
Foo (T);
T get();
private:
T data;
};
#include "foo_impl.h"
#endif
foo_impl.h
This one is bit different from the norms. Here we are not guarding the header file content. Instead we will raise an error if some one included foo_impl.h directly (which in our case does not make sense).
#ifndef FOO_H
#error 'foo_impl.h' is not supposed to be included directly. Include 'foo.h' instead.
#endif
template <class T>
Foo <T> :: Foo (T stuff) {
data = stuff;
}
template <class T>
T Foo <T> :: get () {
return data;
}
Now if some one tries to include foo_impl.h directly will get error like:
foo_impl.h:2:2: error: #error 'foo_impl.h' is not supposed to be included directly. Include 'foo.h' instead.
PROS:
Separation of concerns, implementation and declarations are in separate files.
Safe guarding implementation file avoid accidental inclusion.
The header file used to include is not bloated with implementation code.
CONS:
As mentioned above, have to share the implementation.
NOTE: For not sharing code for templates, I think you already know that you have to declare all possible types in the which the end user can use it.
Including .cc files is bad news and defeats the purpose of separating implementation from declaration.
Define templates in headers:
#ifndef FOO_H
#define FOO_H
template <class T>
class Foo {
public:
Foo (T);
T get ();
private:
T data;
};
// implementation:
template <class T>
Foo :: Foo (T stuff) {
data = stuff;
}
template <class T>
T Foo <T> :: get () {
return data;
}
#endif
If you really prefer 2 files then make the second one a .h too. Name it foo_impl.h or something.
It is common to affect the seperation of interface and implementation for templates by #includeing the implementation of the templates at the end of the header, but there are three problems with how you are doing it:
You're including the .h file in the .cc file. Don't; there should be nothing but function definitions in the implementation file.
You're .cc file should not be named .cc, it should be named .template or something similar to let people know that it should not be compiled (like headers should not be compiled)
The #include "foo.cc" in foo.h should be inside the include guards, not outside.
Done this way, there is no extra work for the user to be done. All you do is #include the header, and you're done. You don't compile the implementation.
Since you are including foo.cc in foo.h, you'll make your life simpler by putting all the code into foo.h and getting rid of foo.cc. There is no advantage to be gained from splitting the code into two pieces.
export keyword is deprecated in c++11. So, you will end up with deprecated code. You put your defintions in the header file itself.

#include .h or .cpp file?

So I have this weird looking problem: my very basic program generates an error message (undefined reference to 'foo::foo(int)') when i import the .h file of a separate class. However, when I change the import file to .cpp, it all works.
Now, I've read a little, and seen a few video tutorials, and they all say the same: import the .h file. So why doesn't it work?
I use Code::Blocks, where i compile and run(no command lines), in Windows 7. I do suspect that something isn't set up quite right, however, I do want to know for sure if it is my code that fails.
Main.cpp:
#include <iostream>
#include "Foo.h" //This don't work. If i include Foo.cpp it does.
using namespace std;
int main()
{
Foo k(10);
cout << k.getInt() << endl;
}
foo.h:
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo(int tall);
int getInt()const;
protected:
private:
int m;
};
#endif
Foo.cpp:
#include "Foo.h"
Foo::Foo(int tall)
: m(tall)
{
//ctor
}
int Foo::getInt()const
{
return m;
}
You need to compile both main.cpp and foo.cpp and link the 2 resulting object files together.
You are failing to compile and/or link the Foo.cpp file when you do your linking step. I'm not familiar with Code::Blocks though, so I can't tell you how to fix it.
Right-click on your .cpp file and go to properties. On build tab make sure compile, link, debug, and release are checked.