954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to change the value of extern variable

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

peuceul
Newbie Poster
2 posts since Jul 2011
Reputation Points: 10
Solved Threads: 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;

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

extern s are used to "pass" variables from one sourcefile 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.)

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: