Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining extern array from different files

Tags:

c

extern

I am declaring an array of structures, and want to define the first array component in one file and second array component in another file. The following is an example.

header.h

struct st1 {
  int a;
  int b;
}

file1.c

struct st1 structure1[2];

I want to use initialize structure1 components from different files as below

file2.c

extern struct st1 structure1[0] = { 10, 100 };

file3.c

extern struct st1 structure1[1] = { 200, 500 };

Also please note that in file2.c and file3.c, the definitions are not inside functions.

If I try to compile, linker throws errors for multiple definition. After searching with Google, I got to know that the definition of extern can happen only once. Can we accomplish such kind of definition of extern array in different source code files?

Some more information: file2.c and file3.c have constants, which I will be using in file1.c. My current implementation is I am using init() functions in file2.c and file3.c. file1.c uses initialized values to decide the course of execution. Since file2.c and file3.c are exporting constants, my intention is to avoid 2 additional init calls from file1.c.

like image 265
Ven Avatar asked Mar 16 '23 14:03

Ven


1 Answers

I've tried to make sense of what you want as much as possible, I think you would need to organise your files like below.

The header file would contain the shared symbols references that are available throughout the project as well as a few functions:

////// header.h //////
struct st1 {
    int a;
    int b;
};

extern struct st1 structure1[2];

extern void init2();
extern void init3();

Then, the implementation that contains the symbol; you could do the initialisation here as well:

////// file1.c //////
#include "header.h"

struct st1 structure1[2];

Then, the codes files in which you would do the structure changes; because this can't happen at compile time, you need to wrap this inside a function that you would call from somewhere else.

////// file2.c //////
#include "header.h"

void init2()
{
    structure1[0] = (struct st1){10, 100};
}

////// file3.c //////    
#include "header.h"

void init3()
{
    structure1[1] = (struct st1){200, 500};
}

The above two scripts have an initialise function that can be called to write into the structure. Finally, an example that demonstrates the behaviour:

////// main.c //////
#include "header.h"
#include <stdio.h>

int main(void)
{
    init2();
    init3();

    printf("s[0].a = %d, s[1].a = %d\n", structure1[0].a, structure1[1].a);

    return 0;
}

Compile like so:

cc -o file file1.c file2.c file3.c main.c
like image 56
Ja͢ck Avatar answered Mar 30 '23 18:03

Ja͢ck