Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial struct X*
types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
value.h
relies on chunk.h
, which relies on value_array.h
, which relies on value.h
.
Originally - chunk.h
used to rely directly on value.h
as well. I have managed to eliminate that dependency by having addConstant
take a struct Value*
instead of Value
.
But I still haven't figured out how I can remove the dependency between value_array.h
and value.h
. The problem is that functions in value_array.c
need to know the sizeof(Value)
, and so their signature can't take the partial type struct Value*
.
Suggestions would be welcome.
The slightly simplified code:
value.h
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
chunk.h
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
value_array.h
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
value_array.c
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}