954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C variables run time problem

Can anybody help me on this problem:

I am writing a simulation program with several files. In a header file, I declared e global variable in hope that all other files could use it. so i put down: #define size 100 int memory[size]; in the header file memory.h. However, there are two seperate C files using that variable: simulation.c and processor.c. When I run the program, simulation.c did load all the stuff in the variable memory[size]; but when the program reaches to functions from processor.c, all the loaded stuff in variable memory[size] lost, as if the function in processor.c actually reinitialised the variable. I checked everywhere in processor.c, don't see anywhere the function can initialise the variable. I also tryed to add 'extern' in front of the definition, but end up with compiling error:
Error: Unresolved external '_memory' referenced from C:\DOCUMENTS AND SETTINGS\RS1249\CBPROJECT\SIMULATOR\WINDOWS\DEBUG_BUILD\SIMULATOR.OBJ

I don't know what to do now. Please can somebody help me on this. Thanks

robert_sun
Newbie Poster
9 posts since Jan 2005
Reputation Points: 10
Solved Threads: 0
 

The easiest way to get a truly global variable (accessible across multiple translation units) is to declare it in the common header, and define it in a special translation unit:

/* header.h */
#include "defs.h"

extern int memory[SIZE];
/* header.c */
#include "header.h"

int memory[SIZE];

Now you can include header.h in your other source files, compile and link header.c along with the rest of your project, and everyone can use the memory array.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You