【问题标题】:using C struct that is declared later使用稍后声明的 C 结构
【发布时间】:2012-02-05 21:43:15
【问题描述】:

我想使用一个尚未定义的 typedef 结构,但它是稍后定义的。 有没有类似结构原型的东西?

文件容器.h

// i would place a sort of struct prototype here
typedef struct 
{
 TheType * the_type;
} Container;

文件类型.h

typedef struct {......} TheType;

文件 main.c

#include "container.h"
#include "thetype.h"
...

【问题讨论】:

  • 不确定您要在 TheType 和 Container 之间建立什么样的关系。你具体问的是什么?
  • @octopusgrabbus 他想“转发声明typedef

标签: c coding-style typedef forward-declaration


【解决方案1】:

替换这一行:

// i would place a sort of struct prototype here

这些行:

struct TheType;
typedef struct TheType TheType;

由于您需要在定义Container 类型之前定义类型TheType,因此您必须使用TheType 类型的前向声明 - 为此您还需要结构TheType 的前向声明。

那么你不会像这样定义 typedef TheType

typedef struct {......} TheType;

但你会定义结构TheType:

struct {......};

【讨论】:

【解决方案2】:

在 container.h 中:

struct _TheType;
typedef struct _TheType TheType;

比在type.h中:

struct _TheType { ..... };

【讨论】:

  • 这是正确答案;对于 OP 的进一步说明,这里所做的称为“前向声明”。
  • _ 开头后跟大写字母的标识符是保留标识符
  • 对不起。我记得规则有些不同。
【解决方案3】:

你可以在 typedef 中声明一个结构体:

typedef struct TheType_Struct TheType;  // declares "struct TheType_Struct"
                                        // and makes typedef
typedef struct
{
    TheType * p;
} UsefulType;

请注意,在 C89 和 C99 中可能只有 at most one typedef in one translation unit(这与 C11 和 C++ 不同)。

稍后您必须定义实际的struct TheType_Struct { /* ... */ }

【讨论】:

    【解决方案4】:

    你不能定义一个尚未定义的 struct 的对象;但是你可以定义一个指向这样一个struct的指针

    struct one {
        struct undefined *ok;
        // struct undefined obj; /* error */
    };
    
    int foo(void) {
      volatile struct one obj;
      obj.ok = 0;               /* NULL, but <stddef.h> not included, so 0 */
      if (obj.ok) return 1;
      return 0;
    }
    

    上面的模块是合法的(用gcc编译没有警告)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多