John
John

Reputation: 804

is it possible to declare a large array as static and use it as extern in other files in c

i have a very big array which is shared among many functions in many files in a vc project. My problem is, I have to declare it in main() and use extern in the header files. Since the array is too large for the stack i have to use static which makes it impossible to have the extern declaration in the header files.

How can I solve this problem?

EDIT:

What i did was as you said but i get error LNK2001: unresolved external symbol

Here is my global declaration and the extern declaration:

main.c

static unsigned char bit_table_[ROWS][COLUMNS];

hdr.h

extern unsigned char bit_table_[ROWS][COLUMNS];

ROWS and COLUMNS could grow as large as 1024 and 1048576 respectively

Upvotes: 3

Views: 2962

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490623

By making it static, you're avoiding overflowing the stack (the heap isn't involved), but by placing it inside main no other parts of your program can access it directly.

To share between functions and files in the same program, you must define it outside of main, and put an extern declaration for it in a header that you'll include in the other files that need to access it:

big_array.c:

#include "big_array.h"

int my_big_array[big_size];

in big_array.h:

 #define big_size 1234567

 extern int my_big_array[];

Then any other file that needs access to it just:

#include "big_array.h"

// ...
my_big_array[1234] = new_value;

Upvotes: 4

Carl Norum
Carl Norum

Reputation: 225162

Declare a global pointer and share it among all of your source files (via extern in a header). Then populate that global pointer in main().

Edit:

Your comments on your question seem to indicate that you're confusing the heap with the stack. Just make your array global and share access to it with an extern declaration in a header. Problem solved, and no funny tricks to be pulled.

Upvotes: 6

Related Questions