Search code examples
carraysstructexternstatic-array

Linking an extern static array of structs is not working correctly


I am trying to link a statically defined array of structs. I am using the extern modifier to do so. When I print out the memory address of my extern struct, it differs from the location that it appears to be in the executable.

Here is what I have:

type.h:

typedef struct tableEntry {
     const char *my_str;
     void *my_addr;
     int myint;
} my_struct;

test.c:

include "type.h"

my_struct my_array[] = {
    {"hello", (void*)15, 5000},
    {"world", (void*)15, 3000},
    {"abtest", (void*)15, 2000},
};

main.c:

#include <stdio.h>
#include "type.h"

extern my_struct* my_array;

int main() {
    printf("array location - %p\n", my_array);
    printf("array entry 1 myint - %d\n", my_array[0].myint);
    printf("array entry 1 address - %p\n", my_array[0].my_addr);
    printf("array string location - %p\n", &(my_array[0].my_str));
    printf("array string - %s\n", my_array[0].my_str);
}

I compile the program like so:

gcc test.c main.c

And when I run my executable I get the following output:

array location - 0x4006be
array entry 1 myint - 29811
array entry 1 address - 0x6574626100646c72
array string location - 0x4006be
Segmentation fault (core dumped)

my_array's address in nm output:

0000000000601060 D my_array

As you can see, my output is not what I expect, and my_array is not linked properly (the location in the nm output differs from the location printed by the actual program).

Note: I cannot include the test.c file in my main.c. It must be linked.


Solution

  • Change

    extern my_struct* my_array;
    

    To

    extern my_struct my_array[];
    

    You can't use extern to modify your array into a pointer.