So, I worked a little with the keyword externto better understand what it does.
I have, for example, the following files:
one.h
#ifndef ONE_H
#define ONE_H
extern unsigned global_var;
#endif
one.c
#include "one.h"
unsigned global_var = 10;
two.h
#ifndef TWO_H
#define TWO_H
void print();
#endif
two.c
#include "one.h"
#include "two.h"
#include <stdio.h>
void print() {
frprintf(stdout, "%u\n", global_var);
}
main.c
#include "two.h"
int main() {
print();
return 0;
}
This compiles fine and produces: 10. As expected.
Now if i change
one.h
#ifndef ONE_H
#define ONE_H
#endif
to be essentially empty, and
two.c
#include "one.h"
#include "two.h"
#include <stdio.h>
void print() {
extern unsigned global_var;
frprintf(stdout, "%u\n", global_var);
}
the behavior is exactly the same. That is, my program is still compiling without warnings and exits: 10.
So my question is: what exactly is the difference when creating a global variable anyway? Is one right and the other is not?
Thank,
PS. This has been compiled using gcc -Wallif necessary.
source
share