|
Possibly, but I still use it too.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I am new to C++ I want to define my functions declaration in a seprate header file and definitions in 2 different header files. I am saving the file with .h and .c extension in same folder where main file is located too. I also know that I have to use double quotes to include my files in main. However, I am unable to find the way to define my header file for definitions and declaration. Please give me a small example so that I can get idea about it
|
|
|
|
|
It should be avail able on any tutorial on the net but lets do a basic.
The header file .h is where you put anything that needs to be accessed from another unit. Your functions etc are just prototype declarations. You generally put a guard #ifndef around it to stop it being included multiple times if called from multiple units.
So "mycode.h" would be something like
#ifndef _MYCODE_
#define _MYCODE_
#define DEV_OK 0 // No device error
#define DEV_ERROR -1 // Device access error
void MyFunction1 (int someValue);
int MyFunction2 (void);
#endif
Now for the body file MyCode.cpp
#include "mycode.h"
int CurrentValue = 0;
void MyFunction1 (int someValue){
CurrentValue = someValue;
}
int MyFunction2 (void){
return (currentValue);
}
That is all there is to it as a minimalist code sample.
In vino veritas
|
|
|
|
|
Sir please check the following. There is something wrong. If you correct it for or highlight any improvement factor it will be appreciated.
Header File:
#ifndef _CALCULATION_H
#define _CALCULATION_H
#include "calculation.cpp"
#include "getinput.cpp"
void input_Func(void); void input_Area(void); void input_Trap(void); float rectangle_Area (float , float); float trapezoid_Area (float , float, float);
#endif
Calculation File:
#include "calculation.h"
float rectangleArea (float width, float length)
{
float Area_Rectange = 0;
Area_Rectange = width * length;
return (Area_Rectange);
}
float trapezoidArea (float base1, float base2, float height)
{
float Area_Trapezoid = 0;
Area_Trapezoid = ((base1 + base2)/2) * height;
return (Area_Trapezoid);
}
Input data File:
#include "calculation.h"
void input_Func(void)
{
cout << "\n\nEnter 1 to calculate the area of Rectangle" << endl;
cout << "Enter 2 to calculate the area of a Trapezoid" << endl;
cout << "\n\nEnter your choice : ";
cin >> choice;
}
float input_Area(void)
{
float width = 0, length = 0, answer = 0;
cout << "Enter the width of rectangle :";
cin >> width;
cout << "Enter the length of rectangle :";
cin >> length;
answer = rectangleArea(width, length);
cout << "The area of Rectangle is : " << answer << endl;
break;
}
float input_Trap(void)
{
float base1 = 0, base2 = 0, height = 0, answer = 0;
cout << "Enter base1 of trapezoid : ";
cin >> base1;
cout << "Enter base2 of trapezoid : ";
cin >> base2;
cout << "Enter the height of trapezoid : ";
cin >> height;
answer = trapezoidArea(base1, base2, height);
cout << "The area of Trapezoid is : " << answer << endl;
break;
}
Main File:
#include <iostream>
#include "calculation.h"
using namespace std;
int main()
{
int choice = 0;
char tryagain = 0;
do
input_Func();
switch(choice)
{
case 1:
{
input_Area(); rectangle_Area (float , float);
}
case 2:
{
input_Trap(); trapezoid_Area(float, float, float);
}
default:{
cout << "Neither 1 nor 2 entered." << endl;
}
}
cout << "Do you want to do another calculation? : ";
cin >> tryagain;
}while (tryagain == 'Y' || tryagain == 'y');
return 0;
}
Your help to me in right direction will help me to become a good developer in future. I am completely new in this field. My code is working fine if i put everything in main function. Problem is arising when i am separating declaration and definitions
|
|
|
|
|
The problem is here:
#ifndef _CALCULATION_H
#define _CALCULATION_H
#include "calculation.cpp"
#include "getinput.cpp"
Don't include source files (*.c, *.cpp) using the include statement (especially form within header files).
Also split the header file into two (or three):
- One named calculation.h with the declarations for the calculation.c source file
- One named getinput.h with the declarations for the getinput.c source file
- Optionally one named according to your project name with global declarations used by multiple source files and public declarations for your main.c source file
To build your application each source file must be compiled and the created object files must be aftwerwards linked to create the executable. This is usaully accomplished using a make file. The kind of the make file depends on your development environment. With IDE's you won't see the make file but use options to add source files to your project.
|
|
|
|
|
I would strengthen what Jochen said with you DON'T EVER #include *.c or *.cpp .. NOT EVER ... includes are only .H files. We allow includes to be any sort of file for historic reasons none of which we would ever advise and few programmers would even know.
Please remove these lines they would never be correct anywhere much less where you have them
#include "calculation.cpp"
#include "getinput.cpp"
So with Calculation.cpp you include its own header Calculation.H which you have done ... that's all you need the two files are then linked.
If you need functions in GetInput.cpp then you include GetInput.H which will declare everything that is public from within GetInput.cpp. Do you get it that the .H file limits what you can access as a public everything else in the .CPP is hidden which is the whole point of doing it. You are trying to restrict the chance of making errors by allowing only access to the unit in the way you want. That is why you publish only what you want to allow access to on the interface of the .H file.
In your case Calculation.H doesn't need to know about GetInput.cpp, even if you did need it then you include GetInput.H
So if calculation.cpp needs to know about GetInput.cpp then simply include GetInput.H within calculation.cpp
You seem to be over thinking it
In vino veritas
modified 13-Jun-16 5:06am.
|
|
|
|
|
Thank you everyone for your reply. Can you post in the code form like i showed in my 2nd post. If any link available about explaining this thing please share with me
|
|
|
|
|
Header files just allow the declaration of constants, classes and functions that may be required to be used in more than one implementation file. The implementation (.c or .cpp) then includes the header file, allowing the compiler to have the declarations for any items that the C code uses. See why header files in c - Google Search[^] for further discussions on the subject.
|
|
|
|
|
Okay so this is your Calculation.h file ... which is only changed by removing the two include which are not needed
#ifndef _CALCULATION_H
#define _CALCULATION_H
void input_Func(void);
void input_Area(void);
void input_Trap(void);
float rectangle_Area (float , float);
float trapezoid_Area (float , float, float);
#endif
So now you must provide all that in a Calculation.cpp file which would be all the code below.
So here are the functions you provided but notice I have marked the errors on the 2 functions Input_Area & Input_Trap
So currently only 3 of your 5 functions are correct
#include "calculation.h"
float rectangleArea (float width, float length)
{
float Area_Rectange = 0;
Area_Rectange = width * length;
return (Area_Rectange);
}
float trapezoidArea (float base1, float base2, float height)
{
float Area_Trapezoid = 0;
Area_Trapezoid = ((base1 + base2)/2) * height;
return (Area_Trapezoid);
}
void input_Func(void)
{
cout << "\n\nEnter 1 to calculate the area of Rectangle" << endl;
cout << "Enter 2 to calculate the area of a Trapezoid" << endl;
cout << "\n\nEnter your choice : ";
cin >> choice;
}
float input_Area(void)
{
float width = 0, length = 0, answer = 0;
cout << "Enter the width of rectangle :";
cin >> width;
cout << "Enter the length of rectangle :";
cin >> length;
answer = rectangleArea(width, length);
cout << "The area of Rectangle is : " << answer << endl;
break;
}
float input_Trap(void)
{
float base1 = 0, base2 = 0, height = 0, answer = 0;
cout << "Enter base1 of trapezoid : ";
cin >> base1;
cout << "Enter base2 of trapezoid : ";
cin >> base2;
cout << "Enter the height of trapezoid : ";
cin >> height;
answer = trapezoidArea(base1, base2, height);
cout << "The area of Trapezoid is : " << answer << endl;
break;
}
You main file is correct in that it just includes calculation.h
In vino veritas
modified 13-Jun-16 10:10am.
|
|
|
|
|
Can i have multiple declaration files for different functions. For example; can I have a .cpp file for having input of data and can have a separate file for calculation of data? Is it a correct approach which professional follows? Actually I am confused because of declaration and definitions in septate files. When I write whole code in main it works well as soon as put the code in separate files I started getting error. I removed the .cpp file as I told above and got that concept clear that NEVER include .cpp file in .h header file. I am still getting some function calling error. I am just 1 step away to know where the problem is coming in function call. Please someone correct that portion. i already removed the break from the function as it was mentioned and also got the logical reason behind removing it. Actually I added that break in structure but as I just copy pasted the code in functions I copied it along with it
|
|
|
|
|
Hassan Syed1 wrote: When I write whole code in main it works well as soon as put the code in separate files I started getting error. Which means your compiler/linker options are not correct, but since you failed to share those errors, we can only guess.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
There Errors are explained above your header file declaration does not match your .cpp file. Even in a single file your code for Input_area and Input_trap are both bad and wrong. You will have several warnings which you are just ignoring I take it. Those warnings are real and pointing to a problem you need to fix, which becomes fatal when you turn it to a unit.
You declare this in calculation.h
void input_Area(void);
You have this in your calculation.cpp
float input_Area(void){
LOOK AT THEM .. THEY ARE NOT THE SAME .. the return declare (1st word) differs ... THAT IS YOUR FIRST PROBLEM WITH THE .H FILE
Again we repeat the declaration in the .H file must be EXACTLY the same as the interface actually in the .CPP file.
THERE IS NO EXCEPTION TO THIS RULE .... EVER
So the .H file could be changed to
float input_Area(void);
OR ... the .CPP file could be changed to
void input_Area(void){
I can't work out which definition is correct because you don't actually return anything from input_area. Either could be correct because your code has a big error I can't work out which is right. You have the same problem on float input_Trap. You declared you are returning a float but don't return anything, do you understand what I am saying when I say that????? Even in one big file you will be getting a 2 warnings, something like "function does not return value".
I am struggling why you can't see the problem because you did it correctly in rectangleArea and trapezoidArea, so you know how to return a value when you declare it. So on your code you got right lets mark where you return a float.
float rectangleArea (float width, float length)
{
float Area_Rectange = 0;
Area_Rectange = width * length;
return (Area_Rectange);
}
Now look at Input_area and Input_trap the word return and some value doesn't appear in the code BUT you declared you are returning a float. The compiler and I are both confused with what you are doing. If you declare a float return, then please return one. If you don't want to return a float then change the first word on the declare to void (which matches what you have in the .H file).
On the other issue yes we can move the input stuff to another .CPP and .H file and you generally try and keep units around a theme. However lets just leave it in one first and get that working correctly as you still seem to not grasp the basics and more files just confuses things more.
In vino veritas
modified 13-Jun-16 23:17pm.
|
|
|
|
|
This was the whole code from main file. Please divide it in module form like professional people do so that I can exactly see the problem in my understanding of dividing the project into moduler form
#include <iostream>
using namespace std;
float rectangleArea (float , float); float trapezoidArea (float , float, float);
int main()
{
int choice = 0;
char tryagain = 0;
do
{
cout << "\n\nEnter 1 to calculate the area of Rectangle" << endl;
cout << "Enter 2 to calculate the area of a Trapezoid" << endl;
cout << "\n\nEnter your choice : ";
cin >> choice;
switch(choice)
{
case 1:
{
float width = 0.0, length = 0.0, answer = 0.0;
cout << "Enter the width of rectangle :";
cin >> width;
cout << "Enter the length of rectangle :";
cin >> length;
answer = rectangleArea(width, length); cout << "The area of Rectangle is : " << answer << endl;
break;
}
case 2:
{
float base1 = 0.0, base2 = 0.0, height = 0.0, answer = 0.0;
cout << "Enter base1 of trapezoid : ";
cin >> base1;
cout << "Enter base2 of trapezoid : ";
cin >> base2;
cout << "Enter the height of trapezoid : ";
cin >> height;
answer = trapezoidArea(base1, base2, height); cout << "The area of Trapezoid is : " << answer << endl;
break;
}
default:{
cout << "Neither 1 nor 2 entered." << endl;
}
}
cout << "\n Do you want to do another calculation? : ";
cin >> tryagain;
}while (tryagain == 'Y' || tryagain == 'y');
return 0;
}
float rectangleArea (float width, float length)
{
float Area_Rectange = 0.0;
Area_Rectange = width * length;
return (Area_Rectange);
}
float trapezoidArea (float base1, float base2, float height)
{
float Area_Trapezoid = 0.0;
Area_Trapezoid = height * (base1 + base2)/2;
return (Area_Trapezoid);
}
|
|
|
|
|
How hard is it to put the function signatures in a .h file and the functions themselves in a .c file? Then you just need an additional #include directive, and an adjustment to the make file.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
You are not thinking like a programmer ... at the moment your answers are not needed as you just display them to the console
So one easy option to patch your code in Calculation.CPP is this
void input_Area(void)
{
float width = 0, length = 0, answer = 0;
cout << "Enter the width of rectangle :";
cin >> width;
cout << "Enter the length of rectangle :";
cin >> length;
answer = rectangleArea(width, length);
cout << "The area of Rectangle is : " << answer << endl;
}
That matches your .H header file you don't have to change anything
#ifndef _CALCULATION_H
#define _CALCULATION_H
void input_Func(void);
void input_Area(void);
void input_Trap(void);
float rectangle_Area (float , float);
float trapezoid_Area (float , float, float);
#endif
So you could go and fix input_Trap in the same way I am leaving that as an exercise .. problem fixed.
So there is another alternative which is to return the answer in Calculation.cpp
float input_Area(void)
{
float width = 0, length = 0, answer = 0;
cout << "Enter the width of rectangle :";
cin >> width;
cout << "Enter the length of rectangle :";
cin >> length;
answer = rectangleArea(width, length);
cout << "The area of Rectangle is : " << answer << endl;
return (answer);
}
Now you need to fix the header file Calculation.H
#ifndef _CALCULATION_H
#define _CALCULATION_H
void input_Func(void);
float input_Area(void);
void input_Trap(void);
float rectangle_Area (float , float);
float trapezoid_Area (float , float, float);
#endif
So you could go and fix input_Trap in the same way I am leaving that as an exercise .. problem fixed again.
Look carefully at both answers all that changed is whether you return answer or not. In both cases the .H file matches the .CPP file match.
Either answer is technically correct, there is no way for me to decide because it depends what you intend to do with the unit.
In vino veritas
|
|
|
|
|
Your code is not in a fit state to put in modules .. however I have provided code that does roughly what you want in modules. The code includes error checks on the entry you don't do in any way.
File: Calculation.H
#ifndef _CALCULATION_H
#define _CALCULATION_H
float RectangleArea (float width, float length);
float TrapezoidArea (float base1, float base2, float height);
#endif
File: Calculation.CPP
#include "Calculation.h"
float RectangleArea(float width, float length)
{
float Area_Rectange;
Area_Rectange = width * length;
return (Area_Rectange);
}
float TrapezoidArea(float base1, float base2, float height)
{
float Area_Trapezoid;
Area_Trapezoid = height * (base1 + base2) / 2;
return (Area_Trapezoid);
}
File: Input.H
#ifndef _INPUT_H
#define _INPUT_H
unsigned int MenuInput (char* prompt, unsigned int maxNum);
float GetFloatInput(char* prompt, float min, float max);
#endif
File: Input.CPP
#include <iostream>
#include "input.h"
unsigned int MenuInput(char* prompt, unsigned int maxNum) {
bool validFlag = false;
unsigned int iResult;
do {
printf(prompt);
int err = scanf_s("%u", &iResult);
if ((err == 0) || (iResult > maxNum)) {
printf("Invalid menu choice try again\n");
} else validFlag = true;
scanf_s("%*[^\n]");
} while (validFlag == false);
return (iResult);
}
float GetFloatInput (char* prompt, float min, float max) {
int err;
float fResult;
do {
printf(prompt);
err = scanf_s("%f", &fResult);
if (err == 0) {
printf("Entry is not a float try again\n");
} else {
if (fResult < min) {
printf("Re-enter value below minimum of %f\n", min);
err = 0;
}
if (fResult > max) {
printf("Re-enter value above maximum of %f\n", max);
err = 0;
}
}
scanf_s("%*[^\n]");
} while (err == 0);
return (fResult);
}
File: Source.CPP
#include <iostream>
#include "calculation.h"
#include "input.h"
using namespace std;
float input_area (void) {
float width = GetFloatInput("Enter the width of rectangle :", FLT_EPSILON, FLT_MAX);
float height = GetFloatInput("Enter the length of rectangle :", FLT_EPSILON, FLT_MAX);
return (RectangleArea(width, height));
}
float input_trap(void) {
float base1 = GetFloatInput("Enter base1 of trapezoid : ", FLT_EPSILON, FLT_MAX);
float base2 = GetFloatInput("Enter base2 of trapezoid : ", FLT_EPSILON, FLT_MAX);
float height = GetFloatInput("Enter the height of trapezoid : ", FLT_EPSILON, FLT_MAX);
return (TrapezoidArea(base1, base2, height));
}
int main()
{
bool exitFlag = false;
while (!exitFlag){
printf("\nMain Menu:\n");
printf(" 0) Exit program\n");
printf(" 1) Calculate area of rectangle\n");
printf(" 2) Calculate area of trapezoid\n");
unsigned int choice = MenuInput("Enter your choice : ", 2);
switch (choice) {
case 1:
printf("Area of rectangle = %f\n", input_area());
break;
case 2:
printf("Area of trapezoid = %f\n", input_trap());
break;
default:
exitFlag = true;
}
};
return 0;
}
In vino veritas
|
|
|
|
|
even your code giving error. Have a look at screenshot please. However, Thank you for showing me the correct way to code. I got many point out of it.
Screen Shot of Error = http://i64.tinypic.com/16m0zr4.jpg
|
|
|
|
|
Something funky with GCC compiler but easy to fix include float.h ... its doesn't know what FLT_EPSILON, FLT_MAX are.
These are standard C++ Macro constant definitions so you can just look it up
(float.h) - C++ Reference[^]
So top of Source.CPP becomes
#include <iostream>
#include <float.h>
#include "calculation.h"
#include "input.h"
using namespace std;
In vino veritas
|
|
|
|
|
|
That one is you ... It is basically telling you it can't find the code for GetFloatInput.
GetFloatInput is defined in Input.H and Input.CPP which are included see here
#include <iostream>
#include "calculation.h"
#include "input.h"
using namespace std;
So we are down to either a typo error or you haven't included Input.CPP into your source files. I assume you cut and paste so unlikely to be a typo so lets try number two.
Did you use the menu system and do .... Project... Add files... to add the new .H and .CPP to your source files to the project? I don't use code blocks but it will be something like that.
Can I ask you to show me the line about the deprecated string function points to .. I am interested to see what GCC is complaining about.
There is possibly another warning you are going to get on the definition of main in Source.CPP can you change it from int main() to
int main(int argc, char**argv)
That is the technically correct definition, not the Microsoft shorthand I used.
In vino veritas
modified 15-Jun-16 12:50pm.
|
|
|
|
|
Excellent. Working fine now however I have to remove scanef_s. that _s was creating problem so i only remove _S and scanef remain as it. Now code working fine. Thank you for ur guidance. Now i got the clear idea how to write the code. I will copy the way you wrote this code. I am not a bad student however I like programming but problem is I think i am unable to think like a programmer. I am trying hard for that but no success yet I want to excel in this field but sometimes I stuck
|
|
|
|
|
We all get stuck at times It is really pleasing to see you are willing to apply yourself to learn. None of us are born able to think like a programmer it is like any profession something you get good at by application of lots of time and effort.
Your long single file code is sort of normal basic student level code, it works in a fashion. You are now seeking to move beyond that and I can only encourage that. All I did was really shorten up your code by making functions with more parameters and putting in error checking for things like typing letters instead of numbers etc. There are improvements you could do by using objects or classes but that is more stuff you are yet to learn.
I looked up the problem with scanf_s it is they have changed security with this, you now need to use "%hu" rather than "%u" as meaning a pointer to an unsigned short. That tells you how many years since I have written code for a console application
So there are two fixes to remove the warning correctly
unsigned short iResult;
int err = scanf_s("%hu", &iResult);
In vino veritas
modified 15-Jun-16 14:35pm.
|
|
|
|
|
You are right. i am completely new and it was my class assignment number 1. I finsihed it and submitted it already but then I came to know professionals never write everything in main that's why i decided to search in this direction. By your improved code I can see a boundery wall is set for wrong inputs. Which i wanted to set in my project as well but was not sure how to set those powerful boundaries as you set. I want to excel in this game of programming, I am not an extera ordinary student but i will keep on trying it day by day
Following are few things I extracted from ur code which I am going to follow for the next time code or will at least try my best to do similar things. Correct me if I observed wrong. I did not follow the following things in my code. If I missed any point then point me that as well.
1) You are using braces by giving one space and starting 1st curly brace in-front of the statements like while and if.
2) All variable you wrote in small letters and to make them more clear u out _ sign to link them.
3) Function name 1st character and then the 2nd meaning name of function is capital.
3) 1 step indentation on each step involving in some kind of computation.
4) You used unsigned when you feel that value are in +ve.
modified 15-Jun-16 17:27pm.
|
|
|
|
|
correct on all counts, you have correctly identified that the standard makes the code much more easily readable and helps you identify errors. I enforce the standards at our company and I therefore never write without using that standard. The standard we use is essentially an extension of C99 or sometimes called ANSI-C standard and is used heavily in the sector I work, which is embedded programming.
Companies in the game market you are looking at tend to use C++ (UNREAL GAME ENGINE etc) or C# (UNITY GAME ENGINE) and there standard may differ slightly as the majority of the code won't be C compliant, and they have other pressures for readability. So generally in large companies you will be expected to write to a standard and there will usually be a process to check code into the active repository.
So while learning coding try and have your own standard but just remember you may have to adapt when you are employed. The company is not going to rewrite an entire repository to your standard even if you could argue it was better. So my standard is not the "absolute best" it's just a standard I would generally have to write to at work.
In vino veritas
|
|
|
|
|
i need to set up glut on my windows machine.
i have glut.h in the include\GL folder , libglut32.a in the lib folder and glut32.dll in the windows\system folder
i compile as follows:
g++ -Wall main.cpp -mwindows libglut32.a -lopengl32 -lglu32
i also have the windows.h , gl/glut.h and gl/gl.h included.
and actually my compiler is tdm-gcc (mingw64)
it gives me lots of errors like:
undefined reference to _glutmainloop...
how do i solve this?
|
|
|
|
|