Hi all,

I have a C project consisting of five files as follows:

main.c
file1.c
file1.h
file2.c
file2.h

I have defined an array in file file1.h as follows:

static struct prnc keys[MAXP];

the array was populated in file file1.c

Now I need to use the contents of this array again in file file2.c , I don't get a compilation error when i try to print the cotents of the array in file2.c, but at run time I get nothing as if the code is never encountered. So I tried the following two approaches:

1- I changed the definition of the array in file1.h to:

extern struct prnc keys[MAXP];

This time I got a compilation error generated by references to the array in file file1.c, the error message stated that the array is unknown. Why?
so I tried this:

2- I kept the definition in file1.h as:

static struct prnc keys[MAXP];

and added the following line in file2.c:

extern struct prnc keys[MAXP];

the project compiles but at run time the array seems to be empty.

My question is:

The array is populated in file1.c, and I want to reference its contents in

file2.c

, how can I do that? cause I really don't think that answer is to repopulate it in file2.c! or is it?!


Thanks in advance for your help.

Lose the static qualifier. extern should be placed on the array in the header file to ensure that it's a declaration. Then include file1.h in both file1.c and file2.c. Make sure that the code to fill the array is called first if you define it in file1.c.

That's exactly what I did the first time and which resulted in the compilation error:
"undefined reference to 'keys' "
where keys is the name of the array.
I'm using bloodshed Dev C++ compiler if it makes any difference.
Suggestions?

Ok check this out,

I defined the array in file1.h as:

struct prnc keys[MAXP];

then, I included the following in file2.c:

extern struct prnc keys[MAXP];

and it worked!
Please let me know if you think this is a poor scheme or that I should go about this in another way.
But either way I really appreciate your help, Thank you : )

>Please let me know if you think this is a poor scheme
I think it's a poor scheme, but since it works for you and you can't seem to figure out how to set up your file dependencies properly, go ahead and use it.

But I want to know the proper way if you can kindly tell me,

file1.c has the following header files:

#include "file1.h"

file2.c has the following header files:

#include "file1.h"
#include "file2.h"

But applying the scheme you're suggesting -which is approach #1 in my first post- does not work.

>But I want to know the proper way if you can kindly tell me
I did kindly tell you. Use extern declarations in your header files, provide a single source file for definitions, and the linker will do the rest. You only need a declaration for the code to compile.

This article has been dead for over six months. Start a new discussion instead.