Are header files basically prewritten classes? c++ - c++

Exactly as it states in the title, are header files that you use the #include for basically prewritten/pre coded classes filled with methods and variable that you can use once you include it into your script. Also how can one go about making one to the point where you can simply use header files that you created for your own benefit? A simple explanation will do.

Yes and no... it depends on many things.
An include directive -as for the standard C++ is- can be two things:
#inlclude "filename"
and
#include <header>
The first one literally means "keep the text contained in "filename" and paste it here.
So yes, the file can contain prewritten classes (but not necessaraily have to)
The second one means "let this source to use the facilities the standard defines in its <header> section. As per the standard definition goes, this is not necessarily meant to be a file, although all the implementation I'm today aware of in fact do: header is a file-name and <> and "" simply change the compiler search order.
You can -at this point- cut a "very long Cpp source" into smaller self-contained chunks and come to a cpp file that is nothing more than a sequence of #include and a main().
But that's not all.
A C++ program is not necessarily made by a single cpp file (a cpp file plus everything it includes either directly or indirectly is called "translation unit").
In fact compilation does not produce programs, but "object files" (the term is "ancient operating system terminology", and have nothing to do with object-oriented programming) that a "linker" puts together.
Because a C++ function calling another does not need -to be translated- to know how the other function is translated, but only how its parameters and return values have to be passed and taken, This makes you able to write the other function body in another independently compiled source and let the header to contain only its declaration (not definition).
For example you can have
// fooclass.h
#ifndef FOOCLASS_H
#define FOOCLASS_H
class foo
{
public:
void hello();
void bye();
};
#endif // FOOCLASS_H
,
// out.h
#ifndef OUT_H
#define OUT_H
#include <string>
void printout(const std::string& s);
#endif // OUT_H
,
//main.cpp
#include "fooclass.h"
int main()
{
foo afoo;
afoo.hello();
afoo.bye();
}
,
// fooclass.cpp
#include "fooclass.h"
#include "out.h"
void foo::hello()
{ printout("hello"); }
void foo::bye()
{ printout("bye"); }
,
// out.cpp
#include "out.h"
#include <iostream>
void printout(const std::string& s)
{ std::cout << "- " << s << " -" << std::endl; }
The entire program can be compiled (for example with GCC) as
g++ main.cpp fooclass.cpp out.cpp
or in separated step as
g++ -c main.cpp
g++ -c fooclass.cpp
g++ -c out.cpp
g++ main.o fooclass.o out.o
(if you use MS compilers, you'll most likely do
cl /c main.cpp
cl /c fooclass.cpp
cl /c out.cpp
link main.obj fooclass.obj out.obj
)
Only the last step makes up the program (note that main.cpp will never know about the printout function!). The previous three are required only for files that have been changed, thus on big projects can speed up compilation and distribute tasks to different teams. (there are utiities like make, that allow to automate this thing.
There is an exception to all that, that nowadays is more and more important: templates.
Since they are not implemented as "code to be translated" but as "code to be expanded", they can be translated only when what they have to expand is known.
template<class T>
T max(const T& a, const T& b)
{ return (a<b)? b: a; }
The meaning of (a<b) depends own what the type T actually is. And since it is know only when max is called, max can be expanded as max<int> or max<double> or max<string>
only when used.
For this reason, templates are not normally handled in independent translation units and library offering template classes or functions do that by just providing collection of headers containing all the code, with no source to compile separately.

are header files that you use the #include for basically prewritten/pre coded classes filled with methods and variable that you can use once you include it into your script?
That's the general concept. In C++, not everything needs to be in a class, so there can be non-member functions, types, preprocessor definitions, variables etc. too. Further, some headers declare variables, types and/or functions but do not define them - that means you can make limited use of them and generally have to present the matching implementation object at link or run-time.
Also how can one go about making one to the point where you can simply use header files that you created for your own benefit?
There's no particular magic about it (though there're linking issues above to learn about if you put implementation out-of-line), but to start with just throw some code in a file:
#pragma once
...
...then #include it from another file. If the including file is in directory "X", then you can include headers in directory "X" using e.g. #include "the_header.h" - with double-quoted header filename - even if the include directory is not specified to the compiler as a command line argument.
If you have something in your header that's declared but not defined, then you will want a matching .cc/.cpp file with the definition, which you should compile into an object and link with the code using the library. For example:
mylib.h
#pragma one
int fn(); // declared but not defined
mylib.cc
#include "mylib.h"
int fn() { return 42; } // matching definition
cc -c mylib // compile mylib.o
app.cc
#include "mylib.h"
int main()
{
return fn();
}
cc -o app mylib.o

A common use for header files in c++ is to define methods or classes without having to implement them. It's defining an interface, or telling other parts of your program how it can interact with them. It lets the files doing the including know what they need to know about those classes/methods without telling everything they don't. In the case of methods, you know there's a method doSomethingCool, and you know how to interact with it. As long as you know that you can generally just #include whatever header file doSomethingCool is defined in, and then the linker does its magic at compile time and finds where you called doSomethingCool and "hooks it up" so to speak to the actual implementation code, which you may write say in doSomethingCool.cpp.
Works with functions, classes and variables.

Related

Multiple definition exception in C++

I am starting to learn C++ and am getting this compilation error from my IDE (CodeBlocks). I don't understand why this is happening.
|2|multiple definition of `parser::parseFile()'
|2|first defined here|
I don't see how this could happen. This is my entire code base.
main.cpp
#include "parser/parser.cpp"
int main()
{
return 0;
}
parser/parser.cpp
namespace parser {
void parseFile() {
}
}
Assuming you compiled both main.cpp and parser/parse.cpp you clearly have two definitions of parser::parseFile(): the #include directive just become replaced by the content of the named file (you can use the -E flag with your compiler to see the result).
You probably meant to declare parser::parseFile() in a header file (typically with a suffix .h or .hpp or something like that):
// file: parser/parser.hpp
#ifndef INCLUDED_PARSER_PARSER
#define INCLUDED_PARSER_PARSER
namespace parser {
void parseFile();
}
#endif
... and to include this header file into both translation units.
Your program have violated the One Definition Rule (also known as ODR).
In short, parser::parseFile function have been defined in both of your .cpp files, because on the compiler level, #include <header.h> simply means substituting the entire file contents in place.
Solution to your problem depends on your actual program, though. If you want to solve the ODR rule for class definitions, you can do either of:
1) Add a #pragma once at the beginning on a header. This, although being supported by all major compilers, is not standardized way of protecting from double-including a header.
2) Add an include guard:
#ifndef MY_HEADER_GUARD
#define MY_HEADER_GUARD
// your header contents go here
#endif
If you want to solve the ODR problem for functions and data variables, the above approach won't work because you can still have them defined multiple times in different .cpp files.
For this, you still have 2 options:
1) define your function somewhere outside, namely, in some .cpp file, only leaving its declaration in the header:
// header.h
namespace parser {
void func();
}
// file.cpp
void parser::func() { ... }
2) Declare your function as inline, as inline function are allowed to have multiple definitions by the C++ standard (however, they must be strictly identical up to lexem level):
// header.h
namespace parser {
inline void func() { ... }
}
To sum it up, I'd strongly recommend you go both directions by protecting your header from double inclusion and making sure your function is either inline or gets defined in a .cpp file. With the latter, if your function implementation changes, you won't have to recompile all the files that include your header, but only the one that has the functon definition.
Header files ending with .h(usually) is often used to separate class and function declaration from their implementation.
In Code::Blocks you can add header files by right clicking on your project name -> 'Add files' -> create a new file with .h extension. Following good practise, you should also create a .cpp file with the same name where the implementation is written.
As already answered, in your header file you can first write an include guard followed by your include's (if any) and also your function declarations. And in your 'parser.cpp' & 'main.cpp' you will have to #include "parser.h" since the files depend on eachother.

Is there a simpler approach to reuse code in C++ as we do with packages in java? Making a header file is comparatively complicated?

I am using GCC C++ 11 in CodeBlocks IDE. I have been trying to reuse classes that I wrote by putting them into a header file but it doesn't work. I have looked into many books but none has detailed information on making C++ code reusable.
There are a couple concepts that C++ uses that I think you're missing:
The difference between a declaration and a definition
#include statements
Linking against other libraries
In general, one reuses code in C++ by Declaring a function in a header file (.h), Defining it in a source file (.cpp). The header file ("foo.h") is then included in both the source file (foo.cpp) and any other file you want to use something declared in it using and preprocessor include directive #include "foo.h". Finally if the source file in which the functions declared in the header file are defined is not a part of the source for the library or executable that you're compiling, you will need to link against the library in which it was built.
Here's a simple example that assumes that you don't need to link against an external library and that all files are in the same directory:
foo.h:
The class Foo is declared along with a member function foobar and a private member variable barM. In this file we're telling the world that there is a class named Foo, it's constructor and destructor are public, it has a member function named fooBar that returns an integer and it also has a private member variable named barM.
class Foo
{
public:
Foo();
~Foo();
int fooBar();
private:
int barM;
};
foo.cpp
The individual member functions for our class Foo are defined, we implement the things we declared in the header file. Notice the include statement at the top
#include "foo.h"
Foo::Foo()
{
barM = 10;
}
Foo::~Foo()
{
}
int Foo::fooBar()
{
return barM;
}
main.cpp
We use our class in a different file, again the header file is included at the top.
#include <stdio.h>
#include "foo.h"
int main(int argc, char *argv[])
{
Foo flub;
std::cout << "flub's fooBar is: " << flub.fooBar() << std::endl();
return 0;
}
The expected output from this would be:
flub's fooBar is 10.
As a general note, I haven't compiled this code, but it should be enough to give you a basic example of the ideas of declarations, definitions, and include statements.
Seeing as you're coming from Java, I'm actually betting that you got all of that already, the hard part is actually using code from a different c++ library, which is akin to Java packages. Setting this up requires exporting the symbols you desired to use in a different library. The way to do this is compiler specific, but is generally accomplished by defining a Macro in a different header file and then using that macro in the declaration of the item you'd like to export. For gcc, see reference GNU Reference Manual.
To extend the above example you create another header file: fooLibExport.h
#if BUILDING_LIBFOO && HAVE_VISIBILITY
#define LIBFOO_DLL_EXPORTED __attribute__((__visibility__("default")))
#elif BUILDING_LIBFOO && defined _MSC_VER
#define LIBFOO_DLL_EXPORTED __declspec(dllexport)
#elif defined _MSC_VER
#define LIBFOO_DLL_EXPORTED __declspec(dllimport)
#else
#define LIBFOO_DLL_EXPORTED
#endif
foo.h would then be changed to:
#include "fooLibExport.h"
class LIBFOO_DLL_EXPORTED Foo
{
public:
Foo();
~Foo();
int fooBar();
private:
int barM;
};
Finally you'll need to link against the library that Foo was built into. Again this is compiler specific. At this point we're through the setting up of header files for exporting symbols from a C++ library so that functions defined in one library can be used in another. I'm going assume that you can follow the reference material for setting up the GCC compiler for the rest of the process. I've tried to bold the key words that should help refine your searches.
One final note about #include statements, the actual argument isn't just the filename, its the path, relative or absolute, to the file in question. So if the header file isn't in the same file as the file you're trying to include it in, you'll need to use the appropriate path to the file.
Code re-usability casts its net wide in C++ terminology. Please be specific what do you mean by it.C and C++ programming language features usually considered to be relevant to code reuse could be :-
functions, defined types, macros, composition, generics, overloaded functions and operators, and polymorphism.
EDITED IN RESPONSE TO COMMENT:-
Then you have to use header files for putting all declarations which you can use in any file just by including this.

Confused about C++ classes when wanting to use them in another CPP. [Coming from C#]

In OOP, you want to break apart a program into multiple classes.
In C#, you would do as such:
namespace a
{
public class ClassA
{
//Methods...that are defined and have code in them.
}
}
and to use that class, you just do "using namespace a;".
Say I want to create a class in C++, and define them, and put code in them.
class ClassA
{
public:
void methodA();
}
ClassA::methodA()
{
//implementation.
}
To access this implementation, you would just use #include "ClassA.h". I fully understand that, and then you have to implement that code again? That seems counterproductive as I like to spread my project over a lot of classes.
So what would be the proper procedure to implement ClassA and not re-implement all it's methods again?
You don't have to reimplement them in each CPP file, the C++ linker takes care of making sure the definitions get matched together.
All you need is:
A header:
#ifndef FOO_H
#define FOO_H
class Foo{
//Junk goes here
};
#endif
A cpp:
#include "foo.h"
//implementations for junk goes here
void Foo::junk(){
}
And then you can include foo.h. Each cpp will be compiled to a .o file. Than, those .o files are handed to the linker which can figure out where definitions are and piece together the code correctly.
C and C++ have a different way of doing things. As long as you have a declaration for a class, method, or external variable the compiler will happily compile and leave off the actual definition of the methods, classes, etc, for link time. This is simplifying things a lot, but basically the compiler will leave a hint to the linker in the object file, saying that the linker needs to insert the address of the method here.
So you just need to include the "ClassA.h" file and you can compile fine.
Because of this you see some different behavior in C and C++ than you would in C#. For example, in C or C++ it's perfectly fine to have two different items (methods, variables, etc) that are named the same in different files as long as neither one is visible outside the file. Whereas in C# you would have to use different namespaces or different names. Note - not that I'm saying this is good practice, it's just possible.
The .h header files contain the class specification. The corresponding .cpp files contain the implementation and are compiled to .o files. During development, you would include .h files to access the APIs provided by the class. During compilation/linking stage, you would include the .o files also along with your source files to form the final binary. You don't need to implement anything again, w.r.t to the class you are using.

Possible to compile any .c file in isolation (that is, without a main?)

I currently have a "library-like" .c file (that'll be shown below). I have 2 questions about it:
If I want to see if it compiles well for itself, how can I do it? If I try to gcc it, it will always give a "no main" error, which makes sense, but raises the problem of knowing if a given .c file will compile well or not in "isolation". Can I safely conclude that if the only error raised by the compiler is the "no main" one, my file is fine? An example of where compiling .c files in isolation could be nice would be to determine which includes are in excess, in here.
Is there a point in a simple file like this to define a header with its method / struct declarations and then have such tiny .c file with the code implementation in it?
#ifndef SEMAFOROS
#define SEMAFOROS
#include <signal.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
typedef struct {
sem_t* id;
char* nome;
} Semaforo;
inline void lock(Semaforo* semaforo) {
sem_wait(semaforo->id);
}
inline void unlock(Semaforo* semaforo) {
sem_post(semaforo->id);
}
Semaforo* criarSemaforo(char* nome) {
Semaforo* semaforo = (Semaforo*)malloc(sizeof(Semaforo));
semaforo->id = sem_open(nome, O_CREAT, 0xFFFFFFF, 1);
semaforo->nome = nome;
}
void destruirSemaforo(Semaforo* semaforo) {
sem_close(semaforo->id);
sem_unlink(semaforo->nome);
free(semaforo);
}
#endif
Thanks
To compile it without linking (doesn't require a main entry point):
cc -c file.c -o file.o
Even for a small file that defines routines that will be called from other source files you still want a header file. The header file is how the compiler knows the interface to the routines before the linker ties it all together. If you don't have declarations for functions that are external then the compiler has to make assumptions (usually wrong) about the data types of the parameters. You can declare the functions in every source file where they are used, but the point of header files is so that you just do it once in the header file.
The-c option to gcc seems to be what you are missing, which compiles one .c file to a .o file.
The answer to your second question is 'sure'. It's a good habit not to be typing externs into all the .c files that want to use some shared function or another. Every little .h helps.
For the second question, I'd like to know why!
To answer point 2, keeping declarations in a header file helps you avoid situations like the following.
You decide that you need to keep track of your chickens in file.c:
int number_of_chickens;
In file2.c, you decide that it would be a great idea to represent the number of chickens as a double instead of an int, but you forget to update file.c:
extern double number_of_chickens;
double count_chickens() {
return number_of_chickens;
}
void add_to_chickens(double how_many) {
number_of_chickens += how_many;
}
This will compile just fine. The linker will treat number_of_chickens as a name referencing a 4 bit int in file.c, and an 8 bit double in file2.c.
If you call the count_chickens function, it will return garbage (the high 32 bits of the double will be filled in with the contents of int number_of_chickens, the low 32 bits will be undefined - whatever comes after number_of_chickens in memory).
Even worse, when you call add_to_chickens(1) in file2.c, you will write 8 bytes to a 4 byte storage location, surely causing havoc, but not necessarily causing a runtime error (at least, not right away).
If you keep your external declaration in a common header file, you get a compile time error immediately. If you don't, you instead get an unexplained instability 3 months after you ship.

How can I avoid including class implementation files?

Instead of doing
#include "MyClass.cpp"
I would like to do
#include "MyClass.h"
I've read online that not doing so is considered bad practice.
Separate compilation in a nutshell
First, let's get some quick examples out there:
struct ClassDeclaration; // 'class' / 'struct' mean almost the same thing here
struct ClassDefinition {}; // the only difference is default accessibility
// of bases and members
void function_declaration();
void function_definition() {}
extern int global_object_declaration;
int global_object_definition;
template<class T> // cannot replace this 'class' with 'struct'
struct ClassTemplateDeclaration;
template<class T>
struct ClassTemplateDefinition {};
template<class T>
void function_template_declaration();
template<class T>
void function_template_definition() {}
Translation Unit
A translation unit (TU) is a single source file (should be a **.cpp* file) and all the files it includes, and they include, etc. In other words: the result of preprocessing a single file.
Headers
Include guards are a hack to work around lack of a real module system, making headers into a kind of limited module; to this end, including the same header more than once must not have an adverse affect.
Include guards work by making subsequent #includes no-ops, with the definitions available from the first include. Because of their limited nature, macros which control header options should be consistent throughout a project (oddball headers like <assert.h> cause problems) and all #includes of public headers should be outside of any namespace, class, etc., usually at the top of any file.
See my include guard naming advice, including a short program to generate include guards.
Declarations
Classes, functions, objects, and templates may be declared almost anywhere, may be declared any number of times, and must be declared before referring to them in any way. In a few weird cases, you can declare classes as you use them; won't cover that here.
Definitions
Classes may be defined at most once[1] per TU; this typically happens when you include a header for a particular class. Functions and objects must be defined once in exactly one TU; this typically happens when you implement them in a **.cpp* file. However, inline functions, including implicitly inline functions inside class definitions, may be defined in multiple TUs, but the definitions must be identical.
For practical purposes[2], templates (both class templates and function templates) are defined only in headers, and if you want to use a separate file, then use another header[3].
[1] Because of the at-most-once restriction, headers use include guards to prevent multiple inclusion and thus multiple definition errors.
[2] I won't cover the other possibilities here.
[3] Name it blahblah_detail.hpp, blahblah_private.hpp, or similar if you want to document that it's non-public.
Guidelines
So, while I'm sure everything above is all a big ball of mud so far, it's less than a page on what should take up a few chapters, so use it as a brief reference. Understanding the concepts above, however, is important. Using those, here's a short list of guidelines (but not absolute rules):
Always name headers consistently in a single project, such as **.h* for C and **.hpp* for C++.
Never include a file which is not a header.
Always name implementation files (which are going to be directly compiled) consistently, such as **.c* and **.cpp*.
Use a build system which can compile your source files automatically. make is the canonical example, but there are many alternatives. Keep it simple in simple cases. For example, make can be used its built-in rules and even without a makefile.
Use a build system which can generate header dependencies. Some compilers can generate this with command-line switches, such as -M, so you can make a surprisingly useful system easily.
Build Process
(Here's the tiny bit that answers your question, but you need most of the above in order to get here.)
When you build, the build system will then go through several steps, of which the important ones for this discussion are:
compile each implementation file as a TU, producing an object file (**.o*, **.obj*)
each is compiled independently of the others, which is why each TU needs declarations and definitions
link those files, along with libraries specified, into a single executable
I recommend you learn the rudiments of make, as it is popular, well-understood, and easy to get started with. However, it's an old system with several problems, and you'll want to switch to something else at some point.
Choosing a build system is almost a religious experience, like choosing an editor, except you'll have to work with more people (everyone working on the same project) and will likely be much more constrained by precedent and convention. You can use an IDE which handles the same details for you, but this has no real benefit from using a comprehensive build system instead, and you really should still know what it's doing under the hood.
File Templates
example.hpp
#ifndef EXAMPLE_INCLUDE_GUARD_60497EBE580B4F5292059C8705848F75
#define EXAMPLE_INCLUDE_GUARD_60497EBE580B4F5292059C8705848F75
// all project-specific macros for this project are prefixed "EXAMPLE_"
#include <ostream> // required headers/"modules"/libraries from the
#include <string> // stdlib, this project, and elsewhere
#include <vector>
namespace example { // main namespace for this project
template<class T>
struct TemplateExample { // for practical purposes, just put entire
void f() {} // definition of class and all methods in header
T data;
};
struct FooBar {
FooBar(); // declared
int size() const { return v.size(); } // defined (& implicitly inline)
private:
std::vector<TemplateExample<int> > v;
};
int main(std::vector<std::string> args); // declared
} // example::
#endif
example.cpp
#include "example.hpp" // include the headers "specific to" this implementation
// file first, helps make sure the header includes anything it needs (is
// independent)
#include <algorithm> // anything additional not included by the header
#include <iostream>
namespace example {
FooBar::FooBar() : v(42) {} // define ctor
int main(std::vector<std::string> args) { // define function
using namespace std; // use inside function scope, if desired, is always okay
// but using outside function scope can be problematic
cout << "doing real work now...\n"; // no std:: needed here
return 42;
}
} // example::
main.cpp
#include <iostream>
#include "example.hpp"
int main(int argc, char const** argv) try {
// do any global initialization before real main
return example::main(std::vector<std::string>(argv, argv + argc));
}
catch (std::exception& e) {
std::cerr << "[uncaught exception: " << e.what() << "]\n";
return 1; // or EXIT_FAILURE, etc.
}
catch (...) {
std::cerr << "[unknown uncaught exception]\n";
return 1; // or EXIT_FAILURE, etc.
}
This is called separate compilation model. You include class declarations into each module where they are needed, but define them only once.
In addition to hiding implementation details in cpp files (check other replies), you can additionally hide structure details by class forward declaration.
class FooPrivate;
class Foo
{
public:
// public stuff goes here
private:
FooPrivate *foo_private;
};
The expression class FooPrivate says that FooPrivate is completely defined somewhere else (preferably in the same file where Foo's implementation resides, before Foo's stuff comes. This way you make sure that implementation details of Foo(Private) aren't exposed via the header file.
You needn't include .c or .cpp files - the compiler will compile them regardless whether they're #included in other files or not. However, the code in the .c/.cpp files is useless if the other files are unaware of the classes/methods/functions/global vars/whatever that's contained in them. And that's where headers come into play. In the headers, you only put declarations, such as this one:
//myfile.hpp
class MyClass {
public:
MyClass (void);
void myMethod (void);
static int myStaticVar;
private:
int myPrivateVar;
};
Now, all .c/.cpp files that will #include "myfile.hpp" will be able to create instances of MyClass, operate on myStaticVar and call MyClass::myMethod(), even though there's no actual implementation here! See?
The implementation (the actual code) goes into myfile.cpp, where you tell the compiler what all your stuff does:
//myfile.cpp
int MyClass::myStaticVar = 0;
MyClass::MyClass (void) {
myPrivateVar = 0;
}
void MyClass::myMethod (void) {
myPrivateVar++;
}
You never include this file anywhere, it's absolutely not necessary.
A tip: create a main.hpp (or main.h, if you prefer - makes no difference) file and put all the #includes there. Each .c/.cpp file will then only need to have have this line: #include "main.hpp". This is enough to have access to all classes, methods etc. you declared in your entire project :).
You should not include a source file (.c or .cpp). Instead you should include the corresponding header file(.h) containing the declarations. The source files needs to be compiled separately and linked together to get the final executable.
Cpp files should be defined in your compiler script to be compiled as object files.
What ide are you using?
I am going to assume you are compiling with gcc, so here is the command to compile two .cpp files into one executable
gcc -o myclasses.out myclass.cpp myotherclass.cpp
You should only use #include to include class definitions, not the implentation
One thing you will want to watch out for when including you class declarations from a .h/.hpp is make sure it only ever gets included once. If you don't do this you will get some possibly cryptic compiler errors that will drive you up the wall.
To do this you need to tell the compiler, using a #define, to include the file only if the #define does not already exist.
For example (MyClass.h):
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
// Memebers and methods
}
#endif
// End of file
This will guarantee your class declaration only gets included once even if you have it included in many different .cpp files.