I need to be able to use a pointer to a variable across many files.
I figured out that I could declare the pointer in one of the headers, and then use the variable from different .c files with a simple 'extern' declaration. Unfortunately, this doesn't work - the program won't compile. However, if I flip the order (pointer as extern in header), everything compiles fine.
I don't understand why this happens. Pointer is just a variable after all. I would be grateful for any tips.
This doesn't work:
file1.h
int* int_ptr;
file2.c
#include "file1.h"
extern int* int_ptr;
int_ptr = malloc(sizeof(int));
*int_ptr = 231;
file3.c
#include "file1.h"
int heap_int;
heap_int = *int_ptr
But the following does compile:
file1.h
extern int* int_ptr;
file2.c
#include "file1.h"
int* int_ptr;
int_ptr = malloc(sizeof(int));
*int_ptr = 231;
file3.c
#include "file1.h"
int heap_int;
heap_int = *int_ptr