【发布时间】:2010-02-06 04:13:09
【问题描述】:
我正在尝试找出一种方法,将嵌套的全局结构用作我的 C 库的一种 API 命名空间。
具体来说,我想公开一个 Primary“命名空间结构”,其中包含其他此类结构(例如 Primary.Secondary),这些结构本身包含函数指针 (Primary.Secondary.a_function())。
我已经抽象出以下(相对)简单的示例来说明我想做的事情:
main.c:
#include "Primary.h"
int main () {
Primary.Secondary.a_function();
return 0;
}
Primary.h:
#if !defined(SECONDARY_H)
# include "Secondary.h"
#endif
struct Primary_struct {
struct Primary__Secondary_struct Secondary;
} extern Primary;
Primary.c:
#include "Primary.h"
struct Primary_struct Primary = {
.Secondary = Primary__Secondary
};
Secondary.h:
struct Primary__Secondary_struct {
void (*a_function) (void);
void (*another_function) (void);
} extern Primary__Secondary;
Secondary.c:
#include "Secondary.h"
#include <stdio.h>
void Primary__Secondary__a_function (void);
void Primary__Secondary__another_function (void);
struct Primary__Secondary_struct {
.a_function = Primary__Secondary__a_function,
.another_function = Primary__Secondary__another_function
} extern Primary__Secondary;
void Primary__Secondary__a_function(void) {
Primary.Secondary.another_function();
}
void Primary__Secondary__another_function(void) {
printf("run!\n");
}
当我尝试编译它时,我遇到了以下编译器错误:
> C -O0 Primary.c Secondary.c main.c
Primary.c:3:33: error: initializer element is not a compile-time constant
struct Primary_struct Primary = {
^
1 diagnostic generated.
我应该注意,理想情况下,Primary 和 Primary__Secondary 变量都是 const。我担心增加的复杂性会加剧问题......所以现在,我已经把这方面排除在外了。
问题似乎是,出于某种原因,即使设置为const,并且仅包含编译时存在的元素,Primary__Secondary 结构也不是编译时常量,因此不能存储在编译时的另一个结构。我可能可以通过在运行时设置所有接口来解决这个问题,但是……这似乎是一个非常老套的解决方案。我正在寻找这个问题的任何替代解决方案,你的 C-fu 比我能想出的多。
(注意:这与this question 相关,但有很大不同,而且更加具体。)
【问题讨论】:
-
最好利用您的时间来使用与 C 保持高度兼容性并为您处理所有这些细节的不同语言。如果做不到这一点,听起来你想创建自己的 C 方言,并且可以编写一个简单的解析器来进行最小的转换。
-
你试图做的事情已经被 C++ / Objective C 解决了 ...
-
为什么除了命名函数
PrimarySecondaryAFunction()和PrimarySecondaryAnotherFunction()之外,它还能保护你的命名空间? -
Roger Pate:这可能最终成为我的最终路径;不过,目前我项目的一个设计目标是“在保持高质量 API 的同时使用 C。”因此,退出 C 并不是一个直接的选择。 Francis:是的,而且我对 Objective-C 非常熟悉。但是,它不适合这个项目。
标签: c struct constants global-variables