Search code examples
arrayscstructheader-files

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


I have the below files:

  • swaps.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);
}
  • swaps.h has signature of someFunction
  • poolutils.c has some functions
  • poolutils.h:
#ifndef _POOLUTILS_H
#define _POOLUTILS_H

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

When compiling (gcc -c swaps.c poolutils.c), I am getting the below error:

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[]);

Now, I do include the header where the struct Pool is defined, so swaps.c should know about it but I understand that somehow swaps.h does not, how can I make it aware of the outside definitions ?

(gcc version 10.2.1 20210110 (Debian 10.2.1-6))


Solution

  • Simply add

    #include "./poolutils.h"
    

    to your swaps.h too, if swaps.h needs the Pool struct definition.

    Since you've dutifully put include guards in poolutils.h, you can use the header multiple times in a single compilation unit.

    Alternately, swap the order of your includes; the effect is the same here.

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