As the other answer pointed out, you lied to the compiler about the type of foo
. Hence your program has undefined behavior, which in this case results in a segmentation fault.
When declaring an variable as extern
, you should never put the extern
statement into the .c
file directly. You should always put the extern
statement into a header file and then #include
that header in any .c
file that needs it. But most importantly, you should always include that header in the .c
file that defines the variable, so that the compiler can verify the extern
declaration against the variable definition.
So the code should have consisted of the three files shown below
foo.h
#include <stdint.h>
extern uint32_t *foo;
foo.c
#include <stdint.h>
#include "foo.h"
uint32_t foo[2] = {0xDEADBEEF, 0xCAFEFEED};
main.c
#include <stdio.h>
#include <stdint.h>
#include "foo.h"
int main( void )
{
printf("%p\n", (void *)foo);
printf("%x\n", *foo);
}
In that case, the error messages that you get from gcc
are
foo.c:3: error: conflicting types for ‘foo’
foo.h:2: error: previous declaration of ‘foo’ was here
And, of course, you need to fix the error by fixing foo.h
foo.h
#include <stdint.h>
extern uint32_t foo[];