Ok before I go explaining my problem, note that I have seen the following phenomenon happen in the code that I work on in my company, hence I can't share actual code, instead I will giving some snippets of pseudo C code to explain my problem.
Lets say file1.h contains the following lines of code:
#ifndef FILE1_H
#define FILE1_H
struct data {
int a;
};
struct data foo;
void run(void);
#endif
Now I include this header in another file in the following fashion-:
#include "file1.h"
void run() {
int count = 0;
while(1) {
foo.a = count;
count = (count + 1) % 500;
}
}
Now in the main file I create a thread that points to the run()
method and create a loop that reads from data.foo
in this fashion -:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "file1.h"
void main(void) {
pthread_create(&id, NULL, run, NULL);
while(1) {
printf("Data = %d\n",foo.a);
sleep(1);
}
}
On normal cases this should give a compiler error that there are multiple declarations of the same structure variable. And I have also tried making small sample programs like this - they all fail at compile like they should.
But I have actually seen and worked on code like this that works fine.
In one file I have the variable to which I write data, and in another file I just read the data from it.
Is there any situation that the C compiler allows something like this? Any compiler flags in GCC? I usually build using Makefiles so any obscure compiler flag or switch that allows this behavior?
Or is there a lapse in my understanding of C?
Please excuse other compile-time errors in my code, since this is pseudo code to explain my problem.