Koi Koi - 1 year ago 99
C Question

Including header files in multiple source files in C

Consider the following example:

typedef struct
int value;

void edit(int num);
int get();


My_Struct data={0};

void edit(int num)
data.value = num;
int get()
Return data.value;

If two files file1.c and file2.c both include header.h and file1.c calls the edit function to change value to 99, will a get function called from file2.c return 99 or the initialised 0?

Im hoping it will return 0 and each file has its own copy of My_Struct.

Answer Source

Assuming file1.c and file2.c are linked into a single executable along with header.c, they will be referencing the same variable. So if you call edit with a value of 99 from a function in file1.c, a subsequent call to get from a function in file2.c will return 99.

The only way you could get different results is if you were to pass an instance of My_Struct to these functions, so each calling function could use a different instance.

If on the other hand file1.c and file2.c are each linked into separate executables, then each one (each running instance, actually) will have its own copy of data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download