Answer the question
In order to leave comments, you need to log in
Why does the function in the header file not see the global variable?
I'm reading Stroustrup's book and got stuck on one problem. Get to the point. There are three files: my.h; my.cpp; use.cpp
Content of my.h:
extern int foo;
void print_foo();
void print(int);
#include <iostream>
#include "my.h"
using namespace std;
void print_foo(){
cout << "foo: " << foo << endl;
return;
}
void print(int i){
cout << "i: " << i << endl;
return;
}
#include <iostream>
#include "my.h"
using namespace std;
int main(int argc, char *argv[])
{
int foo = 7;
print_foo();
print(99);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Take it and fuck it. I coded for five minutes - an hour rummaged through the documentation and Google. Over time, the balance will shift to the other side. And now we have a special case https://en.wikipedia.org/wiki/Analysis_paralysis
Everything that is described inside a block (inside curly braces) is visible only inside this block. This is the answer to your "why".
The use of global entities has an extremely negative effect on the quality of the code. Some industry development standards explicitly forbid global variables.
To make it work, you need to move int foo = 7 outside of main.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question