最佳常量 c 约定
假设我想在 C 中声明一组常量(代表应用程序的错误代码)。你会如何将它们分成文件?您会在外部文件中使用枚举并包含它吗?
谢谢, 詹姆斯
Suppose I would like to declare a set of constants in C (representing error codes of an application). how would you divide them into files ? would you use enum in external file and include it ?
Thanks,
James
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,.h 文件中的#defines 或枚举是正确的方法。如果您使用 gdb 等调试器进行调试,枚举会很有用,因为您会看到比数字更具描述性的值。
Yes, #defines or enums in a .h file is the way to go. Enums are useful if you're debugging with a debugger like gdb as you'll see a more descriptive value than a number.
如果它是一组相关的数值,那么
enum
是正确的方法。如果值是 C 字符串或无法用枚举
表示(或者如果它们不能合理地形成一组相关值),则可以使用两种方法之一。使用预处理器
#define
语句,或使用extern const
标记的变量。前者在编译时解析,因此您可以使用它来指定数组长度或在使用时主动调用代码。然而,后者允许您更改常量的值(通过在 .c 文件而不是 .h 文件中指定它),而不必重新编译每个使用它的文件。由于
extern const
标记的变量可以以这种方式进行更改,因此它们更适合在多个项目中重用的代码或作为库分发的代码。然后可以对库进行更改,而无需强制重新编译程序。If it's a set of related numeric values, then an
enum
is the correct approach. If the values are C strings or otherwise not representable by anenum
(or if they don't sensibly form a set of related values), you can use one of two approaches.Either use preprocessor
#define
statements, or useextern const
-marked variables. The former is resolved at compile-time, so you can use it to specify array lengths or to actively call code when used. The latter, however, allows you to change the value of the constant (by specifying it in a .c file rather than a .h file) without having to recompile every file that uses it.Because
extern const
-marked variables can be changed in that fashion, they are preferable in code that is reused across many projects, or code that is distributed as a library. Changes to the library are then possible without forcing programs to be recompiled.如果它是一组值,则在头文件中声明的枚举就足够了(有些人使用#defines,但由于值并不重要,因此枚举在这种情况下工作得很好)。如果您只是想比较错误代码,这是一个很好的方法。
If it's a set of values an enumeration declared in a header file would suffice (some people use #defines but since the value doesn't matter an enumeration works just fine in this case). If you simply want to compare to error codes this is a good method.