im new to the concept of using a header file. Here is my attempt:
my Main.cpp will prompt the user to input an integer. Then it will call the function "ChecknDivide.cpp" by using the header file "ChecknDivide.h".
ChecknDivide.cpp includes two function, one a boolean function - bool isitpositive(int n) that check if the input value is positive.
The other function Void divide(int n) - basically just divide n by 100.
Let's say that i have ChecknDivide.cpp function correctly running, is this the right way to write a ChecknDivide.h file and use it in the main.cpp?
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "AddnDivide.h"
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int x;
cout << "Input an integer: " ;
cin >> x;
AddnDivde(x);
return 0;
}
i get it,it's just declaring the function to let my main.cpp knows the existence of this function.
but what about my "CheckNdivide".h? is my script for the CheckNdivide.h right?
as a matter of course, always add this: #pragma once
at the top of all header files, it will save you the pain of multiple declarations.
also,(you didn't do this, but its a hot tip :>) - never define a variable in a header file, every .cpp file that includes the header will get its own copy of the variable because of what ne555 said above.
And like i said, replace #ifndef #endif with #pragma once.
There's absolutely nothing wrong with the #ifndef/#define/#endif way of preventing multiple inclusion. In fact, many would argue that it's a better way of doing it. While #pragma once is supported by most modern compilers, it's not part of the C++ standard, whereas using #ifndef/#define/#endif is guaranteed to work for all compilers.
> it will save you the pain of multiple declarations.
declare all you want, the problem is with multiple definitions
> never define a variable in a header file,
> every .cpp file that includes the header will get its own copy of the variable
if the variable is declared as static every translation unit would have its own copy
if the variable is declared as extern the variable is shared.
if there is no qualification, the linker complains for multiple definition.
> i get it,it's just declaring the function to let my main.cpp knows the existence of this function.
I wonder what you get it.
In main.cpp you call `AddnDivde(x)', but never say what that is.
Also, ¿what's is stopping you from simply testing your snips and read the error messages?