0

Hi all,

I have a question regarding an extern variable.

---test.c

#include <stdio.h>
#include </home/peuceul/debug/test.h>

extern int a;

int print1()
{
printf("value of a in extern is %d\n", a);
int a = 2;
printf("value of a is %d\n", a);
}

int print2()
{
printf("value of a in second method is %d\n", a);
}

int main()
{
print1();
print2();
}

---test.h

int a = 0;

I am trying to change the value of an extern variable(mainly int a) using print1 method. And in main() I need to call print2 with the changed value of this int a, without passing the "a" as a parameter. I can not figure out how to do it, so far I am using mysql to save the "a" and fetch it later, but I am curious if I can do it in C manner and not using parameter passing to print2 function nor using mysql.

Can anyone point it out?


Thank you

3
Contributors
2
Replies
7
Views
6 Years
Discussion Span
Last Post by WaltP
0

>>int a = 0;

You can not put that in a header file. extern variables are always declared in a *.c or *.cpp file. Put this in the header file extern int a;

0

extern s are used to "pass" variables from one source file to another. Not within a single source file. Remove the extern to make the variable a global and it should work fine (with one more change I leave to you.)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.