Reputation: 17
I am trying to find the variable names of a structure within C. Example:
def.h
typedef struct
{
int fov_one;
int fov_two;
int timing_chain;
...
...
float ratio;
float spare_floats[15];
}PARAMETERS;
The the structure holds places for up to 200 parameters, but only some of them are in use at this time. Currently, the values within the structure PARAMETERS are populated by a a binary file. However, some users would like to change one or two of the values at run-time, after they are populated. I would like to create the option of changing a value based on a string version of the variable name. Such as, if I want to change the variable ratio, I would like the user to be able to enter a string "ratio .25" and replace the current value of "ratio" with ".25".
From what I have read, it is not possible to find a variable based on a string version of the variable name in C due to not having Reflection. Currently, my thought is to parse the header to obtain the variable name, but someone mentioned it may be possible to get the names from the linker before they are striped away. From what I understand, the Compiler/Linker remove the variable names during compilation and use addresses to access variables, not symbols.
I would like to know if it is possible to print out the symbol map containing the variable name and offset that the Compiler/Linker creates.
Using the gcc options
gcc -o foo foo.c -Wl,Map,foo.map
creates a map, but does not contain the variable names of the structure.
Is it possible to extract the variable offset map created by the Compiler/Linker at compile time?
Upvotes: 1
Views: 227
Reputation: 213375
Since you control the source code, the common technique is to generate "name to offset" map at compile time.
For example:
// parameter_fields.inc -- describes fields in struct PARAMETERS
xxx(int, fov_one)
xxx(int, fov_two)
...
xxx(float, ratio)
// def.h
struct _PARAMETERS {
#define xxx(a, b) a b;
#include "parameter_fields.inc"
#undef xxx
} PARAMETERS;
// in somefile.c
#include <stddef.h>
#include "def.h"
struct {
const char *name;
int offset;
} PARAMETER_OFFSETS[] = {
#define xxx(a, b) #b, __offsetof__(struct _PARAMETERS, b),
#include "parameter_fields.inc"
#undef xxx
};
Now you have offsets readily available to your code as part of PARAMETER_OFFSETS
array.
Upvotes: 0
Reputation: 33694
Struct offsets are available as part of the DWARF output (or whatever debugging format your target users). They are also available to compiler plugins.
However, it might be easier to write or generate direct code which updates PARAMETERS
objects based on a string. You might be able to create a more compact representation by listing strings of the field names with their offsetof
values.
Upvotes: 1