在 C header 中定义传递结构的函数

Defining a function that passes a struct in a C header

在使用 header 时遇到一些问题。 我有一个 header data.h,其中包含 typedef struct newPerson 的结构信息。

我的源menu.c中使用了data.h。在 menu.c 中,我有一个函数 void addStudentRecord(newPerson pers)。 代码按预期编译和工作。

但是,我需要将所有功能添加到我的 menu.h header。当我将 void addStudentRecord(newPerson pers); 添加到 menu.h 时,出现此错误 unknown type name ‘newPerson’.

我试图通过添加 #include "data.h 来解决这个问题,但这只会给我带来更多错误。我想知道如何在 header 文件中定义一个接受结构的函数?

听起来您需要 include guards。包含防护可防止头文件被多次包含。

例如,如果您有 menu.h 其中包括 data.h,并且您有 menu.c 其中包括 data.h menu.h,然后 data.h 中的所有内容都被包含两次,这会导致各种错误。

通过添加如下所示的包含防护,您可以保证 data.h 的主体仅包含一次

// data.h

#ifndef DATA_H
#define DATA_H

// the rest of data.h goes here

#endif /* DATA_H */

一些编译器允许您使用 #pragma once 来做同样的事情

// data.h

#pragma once

// the rest of data.h goes here

您可以将指向不完整结构类型的指针传递给函数,但如果要传递结构的副本,它必须是完整类型。也就是说,您必须使完整的 struct structname { ... } 定义可见才能传递结构的副本。

data.h 中定义的类型似乎是不完整的类型,因此您不能使用它来声明需要结构副本的函数。但是您可能希望函数无论如何都接受指向结构的指针。

另请参阅:

  • How do I typedef an implementation-defined struct in a generic header?
  • Does the C standard consider that there are one or two struct uperm types in this header?