最佳常量 c 约定

发布于 2024-11-26 01:14:38 字数 82 浏览 0 评论 0原文

假设我想在 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吻泪 2024-12-03 01:14:38

是的,.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.

听风念你 2024-12-03 01:14:38

如果它是一组相关的数值,那么 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 an enum (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 use extern 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.

权谋诡计 2024-12-03 01:14:38

如果它是一组值,则在头文件中声明的枚举就足够了(有些人使用#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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文