【问题标题】:C forward declaration of struct in headerC 头文件中结构的前向声明
【发布时间】:2013-07-28 23:06:38
【问题描述】:

我正在尝试在函数中传递struct 指针。我在 file1.h 中有一个 typedef,并且只想将该标头包含到 file2.c,因为 file2.h 只需要指针。在 C++ 中,我会像在此处那样编写,但使用 C99 则行不通。如果有人对如何在没有完整定义的情况下传递 struct 指针有任何建议,我们将不胜感激。编译器 - gcc。

file1.h

typedef struct
{
    ...
} NEW_STRUCT;

file2.h

struct NEW_STRUCT;

void foo(NEW_STRUCT *new_struct); //error: unknown type name 'NEW_STRUCT'

file2.c

#include "file2.h"

#include "file1.h"

void foo(NEW_STRUCT *new_struct)
{
    ...
}

【问题讨论】:

  • “它不起作用。” 解释一下。你有编译器错误吗?链接器错误?运行时崩溃?发生了什么?
  • 抱歉,忘记了。它不会像那样编译,如果我将struct 添加到函数参数中,则错误会更改为“函数'foo'参数类型不匹配”。

标签: c struct forward-declaration


【解决方案1】:

我认为你只需要命名你的结构,并对其进行前向声明,然后重新 typedef 它。

第一个文件:

 typedef struct structName {} t_structName;

第二个文件:

  struct stuctName;
  typedef struct structName t_structName

【讨论】:

  • 希望有一个不涉及重新类型定义的解决方案,但我不得不接受这个。
【解决方案2】:

你可以试试这个:

file1.h

typedef struct _NEW_STRUCT  // changed!
{
    ...
} NEW_STRUCT;

file2.h

struct _NEW_STRUCT; // changed!

void foo(struct _NEW_STRUCT *new_struct); // changed!

file2.c

#include "file2.h"
#include "file1.h"

void foo(NEW_STRUCT *new_struct)
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2023-03-12
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多