A
A
ArtemNewDev2016-09-20 04:32:58
Yii
ArtemNewDev, 2016-09-20 04:32:58

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);

Content of my.cpp:
#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;
}

Use.cpp content:
#include <iostream>
#include "my.h"

using namespace std;

int main(int argc, char *argv[])
{
    int foo = 7;
    print_foo();
    print(99);
    return 0;
}

So here's the question. Why doesn't the print_foo function (in the definition file) see the variable I declared in main()? And how to fix it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Inishev, 2016-08-30
@inish777

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

D
Dmitry, 2016-08-30
@slo_nik

here

A
Armenian Radio, 2016-09-20
@ArtemNewDev

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 question

Ask a Question

731 491 924 answers to any question