如何在.h中转发typedef'd结构

era*_*ros 23 c typedef forward-declaration

我有Preprocessor.h

#define MAX_FILES 15

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

typedef struct Preprocessor Prepro;

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}
Run Code Online (Sandbox Code Playgroud)

我意识到我必须将声明与定义分开.所以我创建了Preprocessor.c:

#define MAX_FILES 15

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

typedef struct Preprocessor Prepro;
Run Code Online (Sandbox Code Playgroud)

而Preprocessor.h现在是:

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}
Run Code Online (Sandbox Code Playgroud)

显然,这是行不通的,因为Pr..h不知道Prepro类型.我已经尝试过几种组合,但都没有.我找不到解决方案.

Joe*_*Joe 27

typedef struct Preprocessor Prepro;文件和c文件中的定义与Prepro_init定义一起移动到标题.这将是向前宣布它没有问题.

Preprocessor.h

#ifndef _PREPROCESSOR_H_
#define _PREPROCESSOR_H_

#define MAX_FILES 15

typedef struct Preprocessor Prepro;

void Prepro_init(Prepro* p);

#endif
Run Code Online (Sandbox Code Playgroud)

Preprocessor.c

#include "Preprocessor.h"

#include <stdio.h>

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 预处理器可能是一个糟糕的名称选择,但这取决于你:)同样`FILE`通常用指针引用,`FILE*` (4认同)

San*_*ker 8

如果要隐藏定义Preprocessor,可以将其放在头文件中:

struct Preprocessor;
typedef struct Preprocessor Prepro;
Run Code Online (Sandbox Code Playgroud)

但更一般地说,您可能还需要Preprocessor头文件中的定义,以允许其他代码实际使用它.

  • 第一行是不必要的,因为第二行也将声明`struct Preprocessor`存在而不定义它. (8认同)