Pippi
Pippi

Reputation: 2571

How to use forward declaration in C?

I am writing a C program, and I couldn't find an equivalent example on Stack Overflow. I have 2 files, level.h, lib.h, which depends on the type defined in the other's file. This generates an error, redefinition of typedef 'metalevel_t'/'entry_t' is a C11 feature.

level.h:

#ifndef level_H
#define level_H
#include "lib.h"

// level.h
typedef struct metalevel metalevel_t; 


// key value pairs, value are integers 
typedef struct entry {
    ...
} entry_t;

lib.h:

typedef struct entry entry_t;
typedef struct metalevel{
    entry_t* ...; 
} metalevel_t;

metalevel_t Info[...]; 

However, if I replace entry_t (and metalevel_t) with below, I get typedef requires a name errors.

struct entry {
    ...
};

My Makefile looks like this:

CC=gcc
CFLAGS=-I.
CFLAGS=-std=c99
LDFLAGS = -lm

macro_main: macro_main.o lsm.o lib.o level.o
    $(CC) -o macro_main macro_main.o lsm.o lib.o level.o $(CFLAGS) 

macro_main.o: 

clean: 
      $(RM) macro_main 

How can I use forward declaration in this case?

Upvotes: 0

Views: 672

Answers (1)

M.M
M.M

Reputation: 141554

level.h:

#include "lib.h"

struct entry {
    // ...
};

lib.h:

typedef struct entry entry_t;
typedef struct metalevel{
    entry_t* p;
} metalevel_t;

Not sure what you meant by metalevel_t Info[...]; , that is likely to lead to an error for any possible contents of the ... .

Upvotes: 4

Related Questions