Reputation:
I was wondering if it was possible to use a variable (in my case, an int) that was declared in main, in another .cpp file within my project. I'm trying to do something like this:
MAIN.cpp
#include <iostream>
#include "header.h"
int bar = 4;
int main()
{
std::cout << use_var(); << std::endl;
return 0;
}
header.h
int use_var()
{
return bar;
}
This isn't my actual code, just a very quick written representation of what I'm kinda looking for.
I tried playing a little with extern, but looks like I don't know how to use it correctly, or it isn't the answer to my problem. I don't really know if this is possible in C++ (or any language). I'm not using another .h to declare the variable because it threw me the LNK2005 error (I'm using MSVC++ 2010 Express).
Upvotes: 2
Views: 921