To share a variable, you normally have something like this:
// A.h
extern int key;
void show();
//a.cpp
#include "a.h"
int main() {
key = 1;
show();
};
// b.cpp
#include "a.h"
#include <iostream>
int key;
void show() { std::cout << "Key = " << key; }
There are a couple of points to not here. First of all, you put the extern
declaration in a header, and include it in all the files that use the variable. Define the variable (without the extern
) in one and only one file. Only one file should contain a function named main
.
Edit: to build this, you compile each file by itself, but you have to link the two files together. For example, using gcc you could do something like:
gcc -c a.c
gcc -c b.c
gcc a.o b.o
The first compiles (but does not link) a.c. The second does the same with b.c The third actually links the two together and produces a binary image you can execute (traditionally named a.out
, though, for example, on Windows this is normally changed to a.exe
).