Suppose I have a list of #define
s in a header file for an external library. These #define
s represent error codes returned from functions. I want to wri
You are correct. There's no way to recover preprocessor-defined identifiers at runtime (unless you can read the source, but that's cheating). You would be better off creating a constant array of the names and indexing it with the error code (with proper boundary checks of course) - it should be quite easy to write a script to generate it.
If you definitely want to keep the #define
's I would go with Michael's elegant #define STR(code)
answer. But defines are more C than C++, and the big downside to defines is you can't put them in a namespace. They will pollute the global namespace of any program you include them in. If it's in your power to change it, I would recommend using an anonymous enum instead:
enum{ NO_ERROR ONE_KIND_OF_ERROR ANOTHER_KIND_OF_ERROR }
This is exactly the same as the #define
s you have, and you can put it in a namespace. And now you can use Michael's other answer involving the static const char* const error_names
array yo do what you had originally asked.