Possible to convert list of #defines into strings

前端 未结 8 1095
梦谈多话
梦谈多话 2021-02-05 22:45

Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to wri

相关标签:
8条回答
  • 2021-02-05 23:32

    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.

    0 讨论(0)
  • 2021-02-05 23:35

    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 #defines 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.

    0 讨论(0)
提交回复
热议问题