I will suggest a slightly simpler, albeit maybe not as efficient solution.
This was a solution I came up with for a project after consulting with one of my professors.
Essentially, strings are just ASCII characters, and C file containing variable names can be thought of in the same way.
Thus, suppose you have a list of strings that you would like to turn into variable names for integers.
First, define your structure in a header file that can be accessed by all files in your directory, for instance 'struct.h'.
The first step is to convert the string names to their respective integers
Simply create an empty header, called variable_names.h, include struct.h, and once and for all invoke the following loop in your main file:
const char *strings[] = {"str1", "str2", ... }
fp = fopen("variable_names.h", "a");
fprintf(fp, "#ifndef FILE1_H \n");
fprintf(fp, "#define FILE1_H \n");
fprintf(fp, "extern int* m_integers = {");
int i;
for(i = 0; i < sizeof(strings) - 1; i++){ fprintf(fp, "m.%s,", strings[i]);}
fprintf(fp, "m.%s } ", strings[i+1])
fprintf(fp, "#endif");
Now you have a linear mapping between the string name and value in your structure via the m_integers array. Next is to create some mapping that takes in the string name and points it to this integer. I will use UTHASH, but there are certainly other ways.
Thus, in your main file,
#include "uthash.h"
#include "variable_names.h"
...
struct opcode_table{
char* opcode_key;
int opcodes_val;
UT_hash_handle hh;
};
struct opcode_table *mapping = NULL;
struct opcode_table* s = NULL;
for (int i = 0; i < opcode_size; i++){
s = (struct opcode_table*) malloc(sizeof(*s));
s->opcodes_key = strings[i]; // the string
s->opcode_val = m_integers[i]; // the integer
HASH_ADD(hh,mapping, opcodes_key, sizeof(int),s);
}
^ Please go easy on the code, just a rough example of what could be done. I'm sure there are some mistakes, but high level I believe this should work.
As on overview, the idea is essentially, you wrote to an external file the ascii characters "m.string1", which once is written, is interpreted as an integer via the structure definition, yielding you your desired outcome. Now, you must simply look up the string in the hash table, and you get the integer in the structure.
Also, I would appreciate any feedback if someone finds a better way or this approach is flawed. Thanks!
m.str2
givenm
and the string"str2"
unless you write it. The C language doesn't provide reflection native to the langauge.