3
votes

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

2
I doubt "too large for the heap". Anyway, alloc/initialize the data at program start (static or whatever works) and set up an "extern" pointer provide access to said data. Might also want to look at mmap to keep the data separate...user166390
Show what you've tried so far.Jim Rhodes
@pst: dont you think 24MB of space is "too large"?John
@John - no. I'd imagine pretty much any machine you're using Visual Studio to compiler for can allocate 24 MB without too much effort.Carl Norum
Wait - are you mixing up "heap" and "stack"?Carl Norum

2 Answers

6
votes

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.

4
votes

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;