Results 1 to 5 of 5
hi,
In a c program the value of an integer variable is changing rapidly. I have to get the value of that variable at a particular instant from another program. ...
- 05-12-2010 #1Just Joined!
- Join Date
- May 2010
- Posts
- 2
use of extern in c
hi,
In a c program the value of an integer variable is changing rapidly. I have to get the value of that variable at a particular instant from another program. How can i do it without using a file?
When i tried with extern variable as
prgm 1: update.c:
#include<stdio.h>
#include "header.h"
main()
{
extern int VAR_A, VAR_B;
while(1)
{
VAR_A++;
VAR_B++;
}
}
pgm 2: print.c:
#include<stdio.h>
#include "header.h"
main()
{
extern int VAR_A, VAR_B;
while(1)
{
printf("\nValue of variables are %d %d\n",VAR_A,VAR_B);
}
}
header.h:
#ifndef HEADER_H
#define HEADER_H
int VAR_A, VAR_B;
#endif
i execute the both .c file from 2 terminals but got only value 0 printed for both var_a and var_b all the time
.
regards
vyshakh
- 05-12-2010 #2
extern, as far as I know, has no effect when used on a local variable. It only works for global variables.
Having said that, your program is flawed. You have two separate processes: they cannot simply share a variable like you have them doing. In order for separate processes to communicate, they must use some form of IPC (Interprocess Communication). This can be as simple as using I/O (you read the output from one program into another) to shared memory, where two processes actually use the same portion of memory (changes in one are reflected in the other).
In your particular instance, you would probably want to use two threads, not two processes, in order to see the the effect you're looking for. Threads live within the same process and share everything that is global in the process, such as variables and memory.DISTRO=Arch
Registered Linux User #388732
- 05-12-2010 #3
Here's a link to check out - especially the section on shared memory
6 Linux Interprocess CommunicationsMake mine Arch Linux
- 05-12-2010 #4Just Joined!
- Join Date
- May 2010
- Posts
- 2
thanks for ur reply. I could do it by using threads.
- 05-12-2010 #5Linux Newbie
- Join Date
- Apr 2010
- Location
- Novosibirsk, Russia
- Posts
- 136
declaration a variable as extern just intended to tell linker that this variable used here, but it is declared (as global) in another file (object file, which linker would proceed). Of course, it's about a single project. I often place extern vars just in a header file, and it works fine


Reply With Quote
