header file problem

im abit fatigue from programming all day so forgive me if i keep this short

anyway, i have a problem. the problem is

in my .cpp file, i need to declare the variables in order for it to run with .hpp, otherwise it just says the variables is not declared. then in my main.cpp, it also needs me to declare the same variables in order for it to run, but if i declare it both, then the compiler gives me a multiple declaration error. how do i solve this?
Declare them in your hpp fille.

#include that hpp file in your cpp file.
it is the same, if i do so it will still have multiple declaration because the .o file include the .h and the main also include.h.
So the problem is that actually after compilation you have two objects files declaring the same variables?

Well then declare them only in one cpp file and in the other either mark them as extern (the lazy way) or pass them directly into the functions that need them when you call those functions (the better way).
Last edited on
extern couldnt work, i declare some classes and a bool which i think extern doesnt work?

what does your second statement mean?
extern applies to anything you can create an instance of.

what does your second statement mean?

It means that you're making an object that you want to be used in more than one function, so why not just make it once, in one place, and then use the function parameters to pass it around. Like this:

main.cpp

1
2
3
4
5
int main()
{
  int x = 7;
  int y = increment(x);
}



increment.cpp

1
2
3
4
5
int increment(int input)
{
  input++;
  return input;
}


See how I made the variable x in only one place, and then because the function increment needs to operate on it, I passed it as a parameter? That's what I mean.
Last edited on
Topic archived. No new replies allowed.