Sharing a variable across multiple files

A

aruna.mysore

Hi all,

I have specific question about usage of extern. I want to share a
single variable say int a; across multiple files.

I would define it in file1.c as

int a=0;
int main()
{
.........
a= 20;
..........
}

In another file2.c I would use it as,

int main()
{
extern int a;
................
printf("value of a=%d\n", a);

..................
}

Is this usage right. If yes, how do I run these as two separate
processes so that value changed in file1 is always reflected in file2
whenever it is used in fil2.c. How do I link these two processes put
it in another way.

Regards,
Aruna
 
A

Antoninus Twink

Hi all,

I have specific question about usage of extern. I want to share a
single variable say int a; across multiple files.

I would define it in file1.c as

int a=0;
int main()
{
.........
a= 20;
..........
}

In another file2.c I would use it as,

int main()
{
extern int a;
................
printf("value of a=%d\n", a);

..................
}

Is this usage right. If yes, how do I run these as two separate
processes so that value changed in file1 is always reflected in file2
whenever it is used in fil2.c. How do I link these two processes put
it in another way.

You need to investigate your system's shared memory features. On POSIX
you can used the shm* functions and mmap - here's an extremely simple
example:


/* server.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>

#define MESSAGE "Hello world\n"
#define PATH "/foobar"
#define SIZE 100

int main(void)
{
int shmfd;
char *msg;

if((shmfd = shm_open(PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG)) < 0)
abort();
ftruncate(shmfd, SIZE);

msg = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if(!msg)
abort();
strcpy(msg, MESSAGE);

return 0;
}




/* client.c */

#include <stdio.h>
#include <stdlib.h>

#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

#define PATH "/foobar"
#define SIZE 100

int main(void)
{
int shmfd;
char *msg;

if( (shmfd = shm_open(PATH, O_RDWR, S_IRWXU | S_IRWXG)) < 0)
abort();

msg = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if (!msg)
abort();

printf("%s", msg);
if (shm_unlink(PATH))
abort();

return 0;
}




$ make server client LDLIBS=-lrt
cc server.c -lrt -o server
cc client.c -lrt -o client
$ ./server
$ ./client
Hello world
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top