-1

I want to be able to modify a variable from one C file and see the changes of that variable on the other one

Here are my C files:

file1.c:

#include "myheader.h"

int 
main( void )
{       
    printf("Variable %d\n", var);
} 

file2.c:

#include "myheader.h"

int main(void){
    int var = 1;
    var = var + 1;
}

The header file looks like this:

extern int var;

Now, I want to run file2.c first and than when I run file1.c print the incremented value of var. Ideas?

I think I am doing everything like this answer, but can't make it work.

PS: Just started learning C.

Elsban
  • 1,187
  • 2
  • 13
  • 24
  • 1
    Are you trying to make **two** programs that talk to each other, or are you trying to make **one** program that uses global variables? – user3386109 Nov 28 '15 at 20:05
  • from included link `...multiple source files linked together...`. By now you have two unrelated programs. – kwarunek Nov 28 '15 at 20:05
  • I didn't see the link. I'll answer my own question, you're trying to make one program that uses global variables. The place to start is the [second answer](https://stackoverflow.com/a/1433226/3386109) to that question. – user3386109 Nov 28 '15 at 20:13
  • @user3386109 I am trying to make two programs that talk to each other. – Elsban Nov 28 '15 at 20:16
  • 1
    @Elsban Then you have a lot to learn and SO is not the right forum to teach you from scratch. You are looking for IPC (Inter Process Communication). Mechanisms include [pipe](http://linux.die.net/man/2/pipe), [socket](http://linux.die.net/man/7/socket), [shared memory](http://linux.die.net/man/7/shm_overview) or even just files. – kaylum Nov 28 '15 at 20:19
  • @kaylum I am a Java programmer so I was thinking like static variables work there. You can declare a static variable on a file and access and change it on another one. That is what I am trying to achieve here. – Elsban Nov 28 '15 at 20:22
  • 1
    There is no exact equivalent in standard C. What you can do is [mmap](http://linux.die.net/man/2/mmap) a file in shared mode. Or use one of the other IPC mechanisms already mentioned. – kaylum Nov 28 '15 at 20:32

1 Answers1

1

Each of your "files".c has a main function and thus will compile into a separate executable.

So you can't have one executable increment a variable in its own address space and then have another executable see the change in someone else's address space - the other executable will have an own variable in its own address space. Unless you would use advanced inter process communication (but that is Lesson 42).

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41