I have recently started learning c++ after learning a good amount of Javascript.
I'm pretty sure that the problem I am facing has to do with scope/how many times the header file is #included, but I need some clarification.
If you look at what I have - you can see that I have "int input" commented out in input.hpp, and I have it actually declared in input.cpp within the scope of the getInput() function. Can someone explain in detail why I am able to compile the way it is written here, but it won't compile if I switch where "int input" is declared? NOTE: The error I get is " multiple definition of `input' "
Also, I know this is a long post so if I need to ask this in another post please tell me. Since I am new to C++, have I separated my files correctly?
These are my files:
main.cpp
#include <iostream>
#include "add.hpp"
#include "input.hpp"
int x = getInput();
int y = getInput();
int main()
{
std::cout << add(x, y) << std::endl;
return 0;
}
add.cpp
#include "add.hpp"
#include <iostream>
int addCalc (int x, int y)
{
return (x + y);
}
std::string add (int x, int y)
{
return (std::to_string (x) + " + " + std::to_string (y) + " = " + std::to_string (addCalc (x, y)));
}
add.hpp
#ifndef add_hpp
#define add_hpp
#include <iostream>
int addCalc(int x, int y);
std::string add(int x, int y);
#endif
input.cpp
#include "input.hpp"
#include <iostream>
int getInput()
{
int input;
std::cout << "Enter a number: " << std::endl;
std::cin >> input;
return input;
}
input.hpp
#ifndef input_hpp
#define input_hpp
#include <iostream>
int getInput();
//int input;
#endif
Any and all comments would be appreciated.
Thanks in advance!