c - 将全局结构变量存储在 C 中的另一个全局结构中

标签 c struct constants global-variables

我正在尝试找出一种方法,将嵌套的全局结构用作我的 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.

我应该注意,理想情况下,PrimaryPrimary__Secondary 变量都是 const。我担心增加的复杂性会加剧问题……所以现在,我将这方面排除在外。

问题似乎是,出于某种原因,即使设置为 const,并且仅包含编译时存在的元素,Primary__Secondary 结构也不是编译-time 常量,因此不能在编译时存储在另一个结构中。我或许可以通过在运行时设置所有接口(interface)来解决这个问题,但是……这似乎是一个非常棘手的解决方案。我正在寻找这个问题的任何替代解决方案,你们中的 C-fu 比我能想出的还要多。

(注意:这与 this question 相关,但本质上不同,而且更加具体。)

最佳答案

您正在尝试的事情无法完成;对不起。这是一个浓缩示例:

#include <stdio.h>

int a = 5;
int b = a;

int main(int argc, char *argv[])
{
  printf("Hello, world!\n"); 
  return 0;
}

编译这段代码出现错误:

main.c:4: error: initializer element is not constant

因为编译器不知道如何在编译时进行赋值int b = a。这就是语言的工作方式!

关于c - 将全局结构变量存储在 C 中的另一个全局结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2212021/

相关文章:

c - C中通过void函数初始化指向结构体的指针

c - 尝试将数据从一个结构复制到另一个结构时出现段错误

c++ - 了解 void f(const T& param) 中参数的类型

java - 常量作为字节?

c - C 中的 NULL 混淆

c - 为什么GCC会生成 "mov 0x8,%edx"指令导致崩溃?

c - 注意: expected ‘int * (*)()’ but argument is of type ‘int’

c - if 语句中的逻辑运算符

c++ - 为什么它不能正确解析 XML 文件?

javascript - 传递函数后不要更改对象