When include libraries in .cpp files? - c++

Header are used to separate "declaration" (.h files) from "implementation" (.cpp files), but also to import librareis, so usually there is no #include ..." in the .cpp file.
But let suppose that some-library.h is needed only for some operation done inside a particular implementation of foo() in some .cpp file: should I #include "some-library.h" in the .h file (where the foo() is declared) or include it in the .cpp file (where foo() is implemented)?
I would say the second, since the library is needed only for the implementation, but I would prefer an answer from someone more expert than me on the topic.

You should include your library just where you are using it. If there is no use of the library in your header file then do not include it.
Including it in the header will bring you a lot of headache. For example, you have to distribute it with your project (if your output is a library).

Related

C++ Struct prototyping in separate header file

I am having trouble understanding an answer I saw in another post. It said that it is good practice to define a struct in a separate .h file so it can be used in other files. I think that is great and it solves my current dilemma, however I have a question about compilation and makefiles. I am only familiar with having header files that are associated with .cpp files at the moment.
Can someone explain how that implementation would look when I have a .h and no .cpp? Do I need an implementation file as well? Also, how do I link the header in a makefile? Currently I only know how to compile a .cpp & header into a .o file and link them.
Thanks, and sorry for taking us back to c++ kindergarten. This is a new revelation and seems like a good one.
You don't need a matching source file (.c or .cpp) for every header .h file.
Having header files without corresponding source files is just fine.
When you #include some header file, you can think of it as a kind of "copy and paste" operation: the preprocessor copies the content of the header file, and pastes it in the point of inclusion.
(Well, there are some details to consider here, for example the presence of a #pragma once directive or some #ifdef inclusion guard can prevent multiple inclusions of the same header file in a given project.)
The C and C++ compilers will then process the whole "compilation unit", i.e. the current source file with all the included headers.
The key concept is that you define the struct/class in a .h header, so that you can use it in multiple .cpp files. Whenever you need struct foo defined in foo.h, you #include "foo.h". You don't need to directly compile the header file, it will be pulled in by whichever source file uses it. Therefore you don't need a make target for .h in normal circumstances.
If the definition in the header is never used, it won't be pulled in and that's it.

C++ header and implementation files: what to include?

There is a .h file and a .cpp file with the same name but different extension.
If I want to use what's in the .cpp file, do I include the .h file or the .cpp file?
The simple answer is that you almost always want to include .h files, and compile .cpp files. CPP files are (usually) the true code, and H files are (usually) forward-declarations.
The longer answer is that you may be able to include either, and it might work for you, but both will give slightly different results.
What "include" does is basically copy/paste the file in at that line. It doesn't matter what the extension is, it will include the contents of the file the same way.
But C++ code is, by convention, usually written this way:
SomeClass.cpp -
#include "SomeClass.h"
#include <iostream>
void SomeClass::SomeFunction()
{
std::cout << "Hello world\n";
}
SomeClass.h -
class SomeClass
{
public:
void SomeFunction();
};
If you include either of those, you can use the code from it. However, if you have multiple files that include the same .cpp file, you may get errors about re-definition. Header files (.h files) usually contain only forward declarations, and no implementations, so including them in multiple places won't give you errors about re-definition.
If you somehow manage to compile without errors when including .cpp files from other .cpp files, you can still end up with duplicate code. This happens if you include the same .cpp files in multiple other files. It's like you wrote the function twice. This will make your program bigger on disk, take longer to compile, and run a bit slower.
The main caveat is that this implementation/forward declaration convention doesn't hold true for code that uses templates. Template code will still be handed to you as .h files, but it (usually) is implemented directly in the .h file, and won't have accompanying .cpp files.
Usually it's better to write in the header file .h
#ifndef H_someClass
#define H_someClass
class SomeClass {
public:
void SomeFunction();
};
#endif
so that you won't get errors about re-definition when you need to include the .cpp file in other files.
The .h file usually contains the class declaration and the .cpp file the class definition (implementation). You should include the .h in the .cpp file.
A good rule of thumb is to NEVER include a .cpp file, because the #include directive just copies the content of the included file into the including file. You may end with some multiple inclusion / definition and you definitely don't want to do that.

CPP | .h files (C++)

I was just wondering what the difference between .cpp and .h files is? What would I use a header file (.h) for and what would I use a cpp file for?
In general, and it really could be a lot less general:
.h (header) files are for declarations of things that are used many times, and are #included in other files
.cpp (implementation) files are for everything else, and are almost never #included
Technically, there is no difference. C++ allows you to put your code in any file, with any format, and it should work.
By convention, you put your declarations (basically, that which makes up your API) in the .h files, and are referred to as "headers". The .cpp files are for the actual "guts" of your code - the implementation details.
Normally, you have the header files included with #include by other files in your project (and other projects, if you're making a library), so the compiler can get the interface required to compile. The implementation, in the .cpp files, is typically implemented so there is one .cpp file "filling in" the implementation per .h file.
By convention, .h files is something that you #include. CPP files are something you add to your project for compiling into separate object file, and then passing to the linker.
The .h file is called the header file. You usually put your interface there (the stuff you want to be public). The cpp file is where you actually implement your interface.
First, both are text files that contain code for the C++ compiler or pre-processor. As far as the system is concerned there is no difference.
By convention different file name extensions are used to indicate the content of files. In C programs you tend to see .h and .c files while in C++ .hpp and .cpp serve the same purposes.
The first group, .h and .hpp files, called header files, contains mostly non-executing code such as definitions of constants and function prototypes. They are added to programs via #include directive and used not only by the program or library in question but by other programs or libraries that will make use of them, declaring interface points and contracts defining values. They are also used to set metadata that may change when compiling for different operating systems.
The second group, .c and .cpp files, contain the executing parts of the code for the library or program.
Correct me if I'm wrong but,
When you #include something, it more-or-less inserts the entire included file into the one with the include command; that is, when I include, say "macros.h" in "genericTools.cpp", the entire contents of "macros.h" is placed in "genericTools.cpp" at that point. This is why you need to use things like "#pragma once" or other protections, to prevent including the same file twice.
Of note, templated code needs to be entirely in the file you're going to be including elsewhere. (I'm unsure of this - can template specializations be ommited from the included files, and linked like a normal function?)
The .cpp that is the implementation file is our actual program or code.
When we need to use different inbuilt functions in our code, we must include the header file that is .h files.
These .h files contains the actual code of the inbuilt functions that we use hence we can simply call the respective functions.
Therefore, while we compile our code we can see more number of lines compiled than what we have actually coded because not only our code is compiled but along with that the (code of the) functions (that are included in .h files) are also compiled.

C++ header file convention

I am working on a small game using C++, and I used Eclipse CDT's class generator. It created a .h file with the class definitions and a .cpp file that included body-less methods for said class.
So if I followed the template, I'd have a .cpp file filled with the methods declarations, and a .cpp file with method bodies. However, I can't include a .cpp file within another.
So what is the convention in C++ with classes and include files? What I did was fill in the method bodies right under the class declaration in the .h file, and deleted the .cpp file.
You don't have to include the .cpp file. Including the .h file is all it takes. .h means header, ie, all it should have is function / object definitions. The actual implementations go in the .cpp file of the same name. The linker will deal with straightening it out for you.
The header file contains declarations (also known as prototype). Inclusion of the header lets the program know "I declare something that looks like this exists".
The user of headers saves us the effort of declaring methods all over the place in our code files - we just do it once, then import the file.
The .c/.cpp/.cc file includes the definition - which tells the program what the function does.
You do not have to "include" .c files because that's what the compiler does - it compiles all your .c files into machine code.
One more thing you can do is while creating a header file is to use the preprocessor directive
ifdef and endif. This will prevent your header file being included multiple times.
This is a standard practice which I use whenever I create a new header file.
I'm not quite sure I understand. The header files defines what the class is and can do, and you include that into any source files that need to use the class.
The source file implements how the class does its action.
However, you can include a .cpp into another (you can include anything into anything), but you don't need to.

What is the difference between a .cpp file and a .h file?

Because I've made .cpp files and then transferred them into .h files, the only difference I can find is that you can't #include .cpp files. Is there any difference that I am missing?
The C++ build system (compiler) knows no difference, so it's all one of conventions.
The convention is that .h files are declarations, and .cpp files are definitions.
That's why .h files are #included -- we include the declarations.
The .cpp file is the compilation unit: it's the real source code file that will be compiled (in C++).
The .h (header) files are files that will be virtually copied/pasted in the .cpp files where the #include precompiler instruction appears. Once the headers code is inserted in the .cpp code, the compilation of the .cpp can start.
.h files, or header files, are used to list the publicly accessible instance variables and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.
The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.
A header (.h, .hpp, ...) file contains
Class definitions ( class X { ... }; )
Inline function definitions ( inline int get_cpus() { ... } )
Function declarations ( void help(); )
Object declarations ( extern int debug_enabled; )
A source file (.c, .cpp, .cxx) contains
Function definitions ( void help() { ... } or void X::f() { ... } )
Object definitions ( int debug_enabled = 1; )
However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type> for gcc. Like -x c++ ).
Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.
I know the difference between a declaration and a definition.
Whereas:
A CPP file includes the definitions from any header which it includes (because CPP and header file together become a single 'translation unit')
A header file might be included by more than one CPP file
The linker typically won't like anything defined in more than one CPP file
Therefore any definitions in a header file should be inline or static. Header files also contain declarations which are used by more than one CPP file.
Definitions that are neither static nor inline are placed in CPP files. Also, any declarations that are only needed within one CPP file are often placed within that CPP file itself, nstead of in any (sharable) header file.
A good rule of thumb is ".h files should have declarations [potentially] used by multiple source files, but no code that gets run."
By convention, .h files are included by other files, and never compiled directly by themselves. .cpp files are - again, by convention - the roots of the compilation process; they include .h files directly or indirectly, but generally not .cpp files.
Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:
Source Files for C: .c
Header Files for C: .h
Source Files for C++: .cpp
Header Files for C++: .hpp
Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.