0

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
  • 4
    Variables (pointers or not) should not be defined in header files, as these could be included in several sources, resulting in multiple definitions. Instead, these can be defined in one of the `*.c` files and then declared in the corresponding header as `extern`. – Eugene Sh. Sep 21 '21 at 14:54
  • thanks for your answer however, I've seen many times variables declared in headers - for example in FreRTOS source code. My question was why a pointer in the header file does not compile why( as in the example above). Is it compiler specific? – user7216373 Sep 21 '21 at 14:59
  • 1
    You seem to confuse *declaration* and *definition*. `extern int* int_ptr;` is a declaration which is fine in a header file, `int* int_ptr;` is a definition which should be in exactly one source file (or more correct in exactly one compilation unit.). – Bodo Sep 21 '21 at 15:01
  • 1
    @user7216373, in a sense, yes, it is compiler-specific. Your second example is valid C. Your first is not, but the pattern it exhibits has historically been accepted as an extension by some compilers. – John Bollinger Sep 21 '21 at 15:02
  • No it is not. As I said, you have multiple definitions because now every `*.c` file including this header has its own definition of the same variable. And since it is not `static`, it is not allowed (making it `static` will result in several *different* variables visible in the corresponding `.c` files only). – Eugene Sh. Sep 21 '21 at 15:02
  • 1
    you need to do it right opposite way. `extern` in the .h file, actual definition in the C file :) – 0___________ Sep 21 '21 at 15:21

0 Answers0