Use Public Variable Globally
I'm attempting to modify a MIPS simulator to display the contents of its registers during run time. My question refers to the way in which I plan to do this. So...
I have a file, file1.cpp and file2.cpp. There is a local public variable in file1.cpp called
typedef long ValueGPR;
ValueGPR reg[33];
that I want to access in file2.cpp. Each of these files have a header file. File2.cpp contains a function which iteratively tracks the execution of a prog开发者_如何学运维ram instruction by instruction making this the perfect place to insert a printf("REG[%d]:%d\n",i,reg[i]); statement or something like that but reg is a local variable in file1.cpp. How do I stitch together something that will allow me to access this reg variable?
This is what both files actually look like (after thinking about this a bit more): "File1.h"
typedef long ValueGPR;
...
class ThreadContext {
...
public:
ValueGPR reg[33];
...
...
}
...
"File2.cpp"
...
#include ".../ThreadContext.h"
...
long ExecutionFlow::exeInst(void) {
...
//ADD PRINTF OF reg[1] - reg[32] HERE
...
}
...
I would move the typedef into file1.h along with the following declaration:
extern ValueGPR reg[];
Leave the ValueGPR reg[33];
in file1.cpp.
Cogwheel's answer is correct, but your comment indicates some possibility of confusion, so perhaps it's better to clarify a bit:
file1.h:
#ifndef FILE1_H_INCLUDED
#define FILE1_H_INCLUDED
typedef long ValueGPR;
extern ValueGPR reg[];
#define NUM_REGS 33
#endif
file1.c:
#include "file1.h"
ValueGPR reg[NUM_REGS];
file2.c:
#include "file1.h"
/* ... */
for (i=0; i<NUM_REGS; i++)
show(reg[i]);
Edit: Given the additional point that reg
is really a member of a class, the code above clearly won't work, though the general idea remains the same. For a class member, you'd need to deal with the class as a whole, not just the reg
itself. Taking a wild stab at what things might look like, you could have something like:
file1.h:
// include guard here
class CPU_state {
public:
typedef long ValueGPR;
static const int num_regs = 33;
ValueGPR reg[num_regs];
//or, preferably:
// std::vector<ValueGPR> regs;
// CPU_state() : regs(num_regs) {}
// ...
};
extern CPU_state cpu;
file1.cpp:
#include "file1.h"
CPU_state cpu;
file2.cpp:
#include "file1.h"
for (int i=0; i<cpu.num_regs; i++)
show(cpu.reg[i]);
If you might create more than one CPU at a time, then you'll probably need to pass a pointer or reference to a CPU_state (or whatever you call it) rather than relying on a global instance like this code uses.
精彩评论