C 中的静态初始化
我想要看起来像这样的代码...
static linked_list* globalListHoldingAllSortsOfGoodies = initialize_linked_list();
/* [In a different file...] */
static int placeholder = add_to_global_list(goodies);
但是在 C 中非常量初始化是不可能的。
是否有某种方法可以在不破坏 C89 的情况下获得相同的效果?
关键是通过使用也使用占位符的宏声明好东西,让不同的事物“自动注册”到全局列表中。
I want to have code that looks something like this...
static linked_list* globalListHoldingAllSortsOfGoodies = initialize_linked_list();
/* [In a different file...] */
static int placeholder = add_to_global_list(goodies);
But non-constant initialization is impossible in C.
Is there some way to get the same affect without breaking C89?
The point is to have different things "automatically register" themselves into the global list by declaring the goodies with a macro that also uses placeholder.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以从静态数据构建链接列表。在 ANSI C89(又名 ISO C90)中,它可能如下所示:
在 ISO C99(2000 年由 ANSI 采用)中,您还可以使用复合文字,例如,将
静态分配的节点与动态分配的节点混合是有问题的,因为释放前者会导致在未定义的行为中,因此有必要跟踪哪些节点属于哪个组。
You can build a linked list from static data. In ANSI C89 (aka ISO C90), it could look like this:
In ISO C99 (adopted by ANSI in 2000), you can additionally use compound literals, eg
Mixing statically allocated nodes with dynamically allocated nodes is problematic as freeing the former will result in undefined behaviour, so it will be necessary to keep track of which nodes belong to which group.
好吧,您可以在
main
方法中初始化placeholder
:-)Well, you could initialize the
placeholder
in themain
method :-)不,没有这样的事情。您可以使用静态数据初始化静态变量。添加到列表中并不是“静态”的。
我相信大多数人所做的就是编写一个预处理器来扫描源文件,在“全局列表”中找到您想要的内容,然后生成一个包含适当数据的 .c 文件(例如以 NULL 结尾的静态初始化表) 。
No, there is no such thing. You can initialize static variables with static data. Adding to the list is not 'static'.
I believe what most people do is to write a preprocessor that scans the source files, find the things you want to have in a 'global list' and then generates a .c file with the appropriate data (e.g. NULL-terminated statically initialized table).
正如您所注意到的,C 不具备此功能。如果您无法在 C 之外执行此操作(通过生成 C 代码),那么另一种方法是为每个需要它的模块创建一个initialize() 函数,并确保在适当的时间调用这些函数。
As you've noticed, C doesn't have this capability. If you can't do it outside of C (by generating the C code), then an alternative would be to create an initialize() function for each module that needed it and ensure that the functions were called at the appropriate time.