简体   繁体   English

如何在C中使用前向声明?

[英]How to use forward declaration in C?

I am writing a C program, and I couldn't find an equivalent example on Stack Overflow. 我正在编写C程序,但在Stack Overflow上找不到等效的示例。 I have 2 files, level.h, lib.h, which depends on the type defined in the other's file. 我有2个文件,level.h,lib.h,这取决于另一个文件中定义的类型。 This generates an error, redefinition of typedef 'metalevel_t'/'entry_t' is a C11 feature . 这会产生错误, redefinition of typedef 'metalevel_t'/'entry_t' is a C11 feature

level.h: 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: 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. 但是,如果我在下面替换entry_t(和metalevel_t),则得到typedef requires a name导致typedef requires a name错误。

struct entry {
    ...
};

My Makefile looks like this: 我的Makefile如下所示:

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? 在这种情况下,如何使用前向声明?

level.h: level.h:

#include "lib.h"

struct entry {
    // ...
};

lib.h: lib.h:

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

Not sure what you meant by metalevel_t Info[...]; 不确定metalevel_t Info[...]; , that is likely to lead to an error for any possible contents of the ... . ,可能导致...任何可能内容出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM