Header, function definitions, main in different files - c++

I wanna make a program that's it's going to be in 3 files. "Persona.hpp" "Persona.cpp" "main.cpp" im not sure the way it can be done.
This is "Persona.hpp"
#ifndef __PERSONA_HPP
#define __PERSONA_HPP
#include <string>
using namespace std;
class Persona{
public:
Persona();
void setNombre(string N);
void setFechaNac(string F);
void setPeso(float P);
void setEstatura(float E);
string getNombre(void);
string getFechaNac(void);
float getPeso(void);
float getEstatura(void);
void mostrarDat(void);
private:
string nombre;
string fechaNac;
float peso;
float estatura;
};
#endif
"Persona.cpp"
#include "Persona.hpp"
#include <iostream>
#include <string>
using namespace std;
Persona::Persona(){
nombre = "";
fechaNac = "";
peso = estatura = 0;
}
void Persona::setNombre(string N){
nombre = N;
}
void Persona::setFechaNac(string F){
fechaNac = F;
}
void Persona::setPeso(float P){
peso = (P>1 && P<500) ? P : 0;
}
void Persona::setEstatura(float E){
estatura = (E>30 && E<280) ? E : 0;
}
string Persona::getNombre(void){
return nombre;
}
string Persona::getFechaNac(void){
return fechaNac;
}
float Persona::getPeso(void){
return peso;
}
float Persona::getEstatura(void){
return estatura;
}
void Persona::mostrarDat(){
cout << "\nNombre: " << getNombre();
cout << "\nFecha de nacimiento: " << getFechaNac();
cout << "\nPeso: " << getPeso() << " Kg";
cout << "\nEstatura: " << getEstatura() << " Cm";
}
"main.cpp":
#include "Persona.hpp"
#include <iostream>
using namespace std;
int main(){
Persona humano;
cout << "\nConstructor default: ";
humano.mostrarDat();
humano.setNombre("Jose Ramon Garibay Alvarez");
humano.setFechaNac("27 Octubre de 1989");
humano.setPeso(80);
humano.setEstatura(175.5);
cout << "\n\nEstableciendo datos validos: ";
humano.mostrarDat();
humano.setNombre("Karina Nogueira Briseno");
humano.setFechaNac("15 Agosto de 1985");
humano.setPeso(0.457);
humano.setEstatura(17);
cout << "\n\nEstableciendo datos Invalidos: ";
humano.mostrarDat();
return 0;
}
First of all i'm getting an error: http://oi40.tinypic.com/2v96quo.jpg
and i dont know if im doing right the "#including" files. I remember my profesor was using something like "#ifndef SOMETHING" but i don't know if it is necessary, Thanks for your answers! :)

Use #include "Persona.hpp" instead of #include <Persona.hpp>

Looks like you've got the wrong include directories set.
In addition, you're essentially including your header the "wrong" way, which might be the reason as well:
#include "header.h": Will look in your current code directory (i.e. where your cpp file is) first, when looking for that specific header file.
#include <header.h>: Will look in your system/predefined include directories first.
However, based on your compiler('s) settings, it's version, etc. it's possible that there won't be any difference (unless you've got conflicting file names). It's definitely a good idea to always follow the intended route:
Use #include "..." to include header files that sit somewhere in your source directory. Use #include <...> to include other headers that should be installed on the machine where you're compiling (i.e. external dependencies).
The added note about include guards (either using #ifndef and #define or #pragma once): Those should be used to prevent header files to be included more than once in the same translation unit, e.g. if the same header file is included by two different other headers, you'd end up with redefinitions of variables, structures, classes, etc.
Include guards are an easy way to prevent this behavior; you'll just have to make sure to use a macro that's unique enough.
A basic include guard could be something as simple as this:
#ifndef MY_CUSTOM_HEADER_FILE
#define MY_CUSTOM_HEADER_FILE
// Your header file code
#endif
However, you might agree that this can be rather bothersome and theoretically error prone, e.g. if someone picks common words or names like CUSTOMER or CUSTOMER_H. Due to this, pretty much any modern preprocessor will accept the pragma instruction #pragma once. If that line is in a header file (and active), the compiler will ensure that it's never included more than once:
#pragma once
// Your header file code

If you have different directories for source and header files, please be sure that you locate the correct directory. You might have to change the directory like that:
#include "../Headers/Persona.hpp"

For better programming approach in OOPS always use #ifndef directive in your .h or .hpp file.
start your .hpp like this.
#ifndef __PERSONA_HPP
#define __PERSONA_HPP
and at the ending of your file put this line
#endif
This will take care of many thing and avoid including header file many time.

I remember my profesor was using something like "#ifndef SOMETHING" but i don't know if it is necessary,
#ifndef is a header guard. It is not what is causing your problem, but here's how to use them. You put them at the top of your header like this:
#ifndef SOMETHING_H
#define SOMETHING_H
and at the end of the header you put:
#endif
It basically means that each header gets included exactly once. If you don't have a header guard, you might run into problems.
For example, if you have A.cpp and B.cpp that both #include "header.h", then when the compiler compiles the second one you will get a lot of errors along the lines of "such-and-such class is already defined" or "such-and-such variable is already defined".
But if you have a header guard then when it tries to include the header a second time the #ifndef will fail because SOMETHING_H will have been already defined (when it included the header the first time). So it will skip the whole file until it gets to the #endif and you won't be declaring variables multiple times.
This probably won't be a problem for you if you are only making small projects at the moment, but it is a strongly recommended habit to get into.

Related

Global Constants in .h included in multiple c++ project

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.

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.

C++ Class redefinition error - I cannot figure this out for the life in me

Any help on why I am getting a 'C2011 'Transaction':'class' type redefinition? I'm sure it's glaringly obvious but I cannot for the life of me figure it out. Please help.
transaction.h
#include <string>
class Transaction
{
private:
int amount;
std::string type;
public:
Transaction(int amt, std::string kind);
std::string Report();
};
transaction.cpp
#include "transaction.h"
using namespace std;
Transaction::Transaction(int amt, std::string kind):amount(amt), type(kind)
{
}
string Transaction::Report()
{
string report;
report += " ";
report += type;
report += " ";
report += to_string(amount);
return report;
}
You can either use a header guard in the header file which will make sure you never ever more than once define a class or struct etc. in any other cpp file.
To add a header guard you can simply do this:
#ifndef TRANSACTION_H
#define TRANSACTION_H
// your header file
#endif
Or simply add
#pragma once
to all your header files and you're good.
You need to use include guards in transaction.h:
#if !defined(your_symbol)
#define your_symbol 1
/*ToDo - code here*/
#endif
Where, your_symbol is typically an embellishment of the name of the file. Be careful not to use a leading double underscore or a single leading underscore followed by a capital letter as they are reserved symbols.
This prevents the class declaration from being included more than once in any compilation unit.
You can use #ifndef your_symbol in place of my first line, and drop the 1 from the second line, or perhaps even just use a #pragma once directive at the top of the file, but the version I present works on every compiler I've ever come across.
In your header try this:
#ifndef TRANSACTION //If transaction has never been defined before
#define TRANSACTION //Define transaction
//Content of your header
#endif
This header guard will probably help you. Indeed it will prevent your header from being included multiple times which leads to redefinitions. If you include your header just once you don't need these guards, but it doesn't hurt to have them anyway.
Alternatively, you can use #pragma once at the beginning of your header.
If you want to read more about them, check wikipedia

a.h is included in b.h and I include b.h in my source file, do I need to include a.h in my source file as well?

I am going through an example in a c++ book. And did not understand a certain case.
The main.cpp includes stdexcept.h to use runtime exception. And also includes ErrorHandlingModule.h.
ErrorHandlingModule.h already includes stdexcept.h because of the runtime error parameter it has in the function prototype in it.
The book says I have to include stdexcept.h also in main.cpp. In the source code of the book it is also written that way.
When I remove sdtexcept.h from main.cpp compile passes just fine and program works ok still.
But why the book says that?
Thanks for any answers.
MAIN.CPP:
#include <iostream>
#include <stdexcept>
#include "ErrorHandlingModule.h"
#include "Prompt.h"
// ....
int main(int argc, char* argv[])
{
SAMSErrorHandlingModule::initialize();
do
{
try
{
char Operator = getOperator();
float Operand = getOperand();
cout << Accumulate( Operator, Operand ) << endl;
}
catch( runtime_error RuntimeError )
{
SAMSErrorHandlingModule::handleRuntimeError(RuntimeError);
}
catch(...)
{
SAMSErrorHandlingModule::handleNotaNumberError();
};
}while (SAMSPrompt::UserWantsToContinueYorN("More?"));
return 0;
}
ERRORHANDLINGMODULE.H
#include <stdexcept>
#ifndef _ERROR_HANDLING_MODULE_H
#define _ERROR_HANDLING_MODULE_H
namespace SAMSErrorHandlingModule
{
using namespace std;
void initialize( void );
int handleNotaNumberError( void );
int handleRuntimeError( runtime_error theRuntimeError );
}
#endif // _ERROR_HANDLING_MODULE_H
I think the reason is maintainance. At least, I would do that for this reason. If you eventually decide to switch to "ErrorHandlingModule.h" to something else (e.g. you implement a better error handling strategy and want to use the new one) you don't want the other code into main to break because of this.
This means that if you are using something from stdexcept in your main, apart from using it for input to/output from ErrorHandlingModule, you should include it. Otherwise, I would not include it, since it is not needed when ErrorHandlingModule is not used.
As you noted, this has nothing to do with compilation, as your program compiles just fine if you don't include it into the main. With this respect, however, notice that even if it compiles, it is not always "semantically" correct. In fact, your code might compile even if you remove the inclusion from "ErrorHandlingModule.h" (since stdexcept is included before including ErrorHandlingModule.h). This is the reason why I always prefer to have "..." includes before <...> ones.
Also check this question for a similar discussion.
No, you do not need the #include for stdexcept in both files. The pre-processor will copy the header file into the c file before running through the C compiler. Multiple includes of the same header file can be very problematic which is why the example code uses #ifndef for the header file you are creating to make sure that the header code is only included once. Like Stefano said though, if you no longer include stdexcept and then stop using the ERRORHANDLINGMODULE header file your code will no longer compile.

about headers in C++ when I should use them?

Question about header files in C++: when I should use them. If I write small program should I create header file or can I just declare my classes in .cpp files? What is a good practice? If you give links to articles about it, it would be good. I could not find good ones.
Use header files when you need to share information between several source files. The header file, used carefully, will ensure consistency between a file defining some functionality and other files using that functionality.
When a program consists of a single (source) file, there is no need to create a header. When a program needs more than one source file (say two source files), there must be at least one function or variable 'shared' between the two files (because if there wasn't, one of the files would be redundant). You should have a header to describe the shared function or variables so that the producer and consumer agree on the common functionality.
The corollary is that a header should not describe anything not needed by the consumers of the functionality. Just because the implementation needs to use some second header, the consumer should not be made to include it. If the second header provides definitions used in the interface, then it should indeed be included in the common header.
OK - lots of verbiage. A concrete example:
source1.h
extern int somefunc(int, int);
source1.cpp
#include "source1.h"
int somefunc(int a, int b)
{
return a + b;
}
program.cpp
#include <iostream>
#include "source1.h"
using namespace std;
int main()
{
int x = somefunc(1, 3);
cout << "somefunc(1, 3) is " << x << endl;
}
The header here is necessary to provide the assurance that everything is consistent. Both source1.cpp and program.cpp must include the header to ensure the consistency.
Note that if somefunc() was defined in program.cpp there would be no point in providing the header.
Now suppose we modify somefunc():
source1.cpp - revised
#include "source1.h"
#include <iostream>
using namespace std;
int somefunc(int a, int b)
{
cout << "a = " << a << ", b = " << b << endl;
int x = a + b;
cout << "x = " << x << endl;
return x;
}
Superficially, you could revise source1.h so it includes <iostream>, but that would be a bad move. The interface of the function defined, somefunc(), does not depend on <iostream>, so the header should not include <iostream>.
Header files are always a good idea but strictly speaking you don't need them. Especially when using multiple .cpp files it's strongly recommended to use them.
The rule I used before "always use them" was: any cpp that has its functions accessible from other cpp files should use a header file to "export" the functions.
Best practice: always use header files.
Another reason why you should use header files
when you distributing your binaries. You provide the header file and the dll file to your clients.