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

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.

Related

Is it possible to have more than 1 .cpp file in a project (souce folder)? If so how would the .cpp file communicate?

So, I am working with c++. I know how to link .h file with .cpp (pretty simple stuff.) Problem I am having is that, I don't want to write all my code in one .cpp file, that makes it too big and organization becomes a hustle. In other languages (c# and python) I was able to write a class in a different file then derive children from it, much like header file in c++, but .h files are used only for declaration of the functions and .cpp is where everything is being coded. So, without having a one large .cpp file, can I code it in multiple .cpp files?
Sure. You have one header file with the relevant declarations and then you can have multiple source files implementing them. You only need to make sure that they all are linked together.
It is possible, because when you link them together, it doesn't matter from which translation unit the definitions come from, the only thing that matters is that they exist. There would be no difference if you would have implemented them all in the same translation unit.
It would look like this:
// header.h
// guards...
void func1();
void func2();
// source1.cpp
#include "header.h"
void func1() {}
// source2.cpp
#include "header.h"
void func2() {}

When include libraries in .cpp files?

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

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