3

I read an interesting answer on how to convert a list of error code defines from the error code to the error string using a giant switch statement. I have a slightly different question though.

Given a large text file of thousands of register defines ie:

#define setup_register 0x01

I'd like to be able to take input from the command line like write setup_register 0xFF. Then in my code I'd lookup what setup_register's address was (0x01) and write to it.

Is there a C way to get at the setup_register address? I suppose I could parse the file and create a new one, or do it manually, but that means it has to be done each time it changes.

Community
  • 1
  • 1
confused
  • 713
  • 1
  • 5
  • 16
  • 1
    You say "a large *text* file", but the example content has the form of a C macro definition. Is the file in question in fact a C source file (maybe a header file) that is available during compilation of your program, or is it really used as a plain text file (meaning the program reads it at run time)? – John Bollinger Apr 20 '15 at 17:12
  • Ah sorry for the confusion, it is a very large C source file. A long list of #define statements in the form above. – confused Apr 20 '15 at 19:56

1 Answers1

1

The setup_register is a C preprocessor symbol. Such symbols can be stringified if it is a macro argument. Otherwise as far I as know it cannot be done.

I would write a script in your favorite scripting language (Ruby, Python, Perl) that looks for lines of the form "#define [A-Za-Z_]+ 0x[0-9a-fA-f]+", and then parses out the name and generates an array of structures that has the string and corresponding value. Hash the string, put the structure in a hash table, and you are good to go.

Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46
  • In fact, the preprocessor has an operator (`#`) for converting preprocessor symbols to C strings, so `setup_register` et. al. *can* be available to the code as a string. That doesn't necessarily mean it would be a bad idea to process all those definitions as you describe, but please try to avoid asserting falsehoods. – John Bollinger Apr 20 '15 at 17:21
  • And indeed, one mechanism or another for building a hash table with the strings as keys is certainly the way I would go. – John Bollinger Apr 20 '15 at 17:22