如何在 C 中包含另一个 header 中定义的结构数组?

How to include array of struct defined in another header in C?

我有以下文件:

#include "swaps.h"
#include "./poolutils.h"

double someFunction(struct Pool pools[]){
//do some stuff
}

int main(){
struct Pool pool1 = {"A","C",3.0,9000.0,0.0};
struct Pool pool2 = {"B","D",20.0,20000,0.0};
struct Pool pools[N];
pools[0] = pool1;
pools[1] = pool2;
double a = someFunction(pools);
}
#ifndef _POOLUTILS_H
#define _POOLUTILS_H

struct Pool {
    char *token1;
    char *token2;
    double reserve1;
    double reserve2;
    double fee;
};
//signatures of poolutils.c functions 
#endif

编译 (gcc -c swaps.c poolutils.c) 时,出现以下错误:

In file included from swaps.c:1:
swaps.h:4:44: error: array type has incomplete element type ‘struct Pool’
    4 | double someFunction(struct Pool pools[]);

现在,我在定义 struct Pool 的地方加入了 header,所以 swaps.c 应该知道它,但我知道 swaps.h 不知道,怎么办?我可以让它知道外部定义吗?

(gcc 版本 10.2.1 20210110 (Debian 10.2.1-6))

只需添加

#include "./poolutils.h"

你的 swaps.h 也一样,如果 swaps.h 需要 Pool 结构定义。

由于您尽职尽责地将 include guards 放入 poolutils.h,您可以在单个编译单元中多次使用 header。

或者,调换包含的顺序;这里的效果是一样的

#include "./poolutils.h"
#include "swaps.h"