October 22, 2024
Chicago 12, Melborne City, USA
C++

Circular definition with struct and function in C


I have these two simplified files:

lexer.h

#ifndef LEXER_H
#define LEXER_H

#include "expand_array.h"

// Union to store token value
typedef union {
    //Problem is here bcs of circular definition
    //----------------------------------------
    DynamicCharArray arr; // For identifiers, strings, ...

    int intValue;                       // For integer literals
    float floatValue;                   // For floating-point literals
} TokenValue;

// Structure representing a token
typedef struct {
    TokenValue value;    // Value of the token
} Token;

#endif

expand_array.h

#ifndef EXPAND_ARRAY
#define EXPAND_ARRAY

#include <stdio.h>
#include "lexer.h"

// Definition of the structure for a dynamic array
typedef struct {
    char *stringValue;  // Pointer to a dynamically allocated array of characters
    size_t size;        // Current number of characters in the array
    size_t capacity;    // Capacity of the array 
} DynamicCharArray;

void init_array(Token *token);

void free_array(Token *token);

void add_char(Token *token, int c);

#endif // EXPAND_ARRAY

The problem is, lexer.h needs expand_array.h for DynamicCharArray definition but expand_array.h needs lexer.h for Token definition.
Each definition of function in compilation gets: error: unknown type name ‘Token’

I have looked through other questions regarding forward declarations, but I haven’t found a solution that resolves this specific issue.

How can I restructure this code to resolve the circular dependency while keeping the necessary relationships between these two files?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video