I'm expanding our internal debugging library, and I've run into an odd wall. I'd like to output a variable name as a string. From elsewhere on this site, I found that a macro can be used to do this within a file:
#define VarToStr(v) #v
...
printf("%s\n", VarToStr(MatName));
This outputs MatName
. But now let's try this through a function across files (Matrix is a defined type):
// DebugHelpers.h
#define VarToStr(v) #v
...
void PrintMatrix(const Matrix &InputMat)
{
printf("%s\n", VarToStr(InputMat));
... // output InputMat contents
}
// DataAnalysis.cc
#include DebugHelpers.h
...
void AnalysisSubProgram342()
{
Matrix MatName;
...
PrintMatrix(MatName);
}
This outputs InputMat
, instead of MatName
. How can a function in another file get the variable name from the calling file?
While more complex solutions (wrapper classes, etc.) would be useful for the larger community, my implementation needs to minimize impact to preexisting code/classes.
Update:
Inspired by zenith's comments, I implemented both of his proposed solutions for comparison's sake and got both working quickly. The macro works well for simple outputs, while the function allows for more complex work (and type checking/overloading). I hadn't known that preprocessor macros could be so complex. I'll remember both for future use. Thanks !