首页 > 解决方案 > 为什么使用 struct 有效但 typedef struct 无效?

问题描述

我的代码有问题。

这是我的演示:

我的文件结构是

├── include
│   ├── link.h
│   └── token.h
└── src
    ├── CMakeLists.txt
    └── main.c
//token.h

#ifndef __TOKEN_H__
#define __TOKEN_H__
#include <stdio.h>
#include "link.h"

typedef struct Token{
    char val[30];
}token;

#endif
//link.h

#ifndef __LINKLIST_H__
#define __LINKLIST_H__
#include <stdio.h>
#include "token.h"

typedef struct Linklist{
    token* elem;          
    struct Linklist *next;  
}linklist;

#endif
//main.c

#include <stdio.h>
#include "token.h"
#include "link.h"
#include <stdlib.h>
#include <string.h>

int main(){
    linklist* head = (linklist*)malloc(sizeof(linklist));
    head->elem = (token*)malloc(sizeof(token));
    strcpy(head->elem->val, "111");
    printf("%s\n", head->elem->val);
}
//CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(test VERSION 0.1.0)

include_directories(../include)

add_executable(test main.c)

进入src文件,编译这个demo

mkdir build && cd build 
cmake ..
make

然后出现一个错误:

error: 
      unknown type name 'token'
    token* elem;          
    ^
1 error generated.

但是我们不使用typedef,只使用struct Token,一切都会好的。

修改版本为:

//token.h

struct Token{
    char val[30];
};

//link.h

typedef struct Linklist{
    struct Token* elem;          
    struct Linklist *next; 
}linklist;
//main.c

head->elem = (struct Token*)malloc(sizeof(struct Token));

我想问为什么会出现这种情况?

标签: cstructtypedef

解决方案


你有一个循环包含依赖,你需要打破这个循环。

常见的方法是停止在头文件中包含不需要的文件,并在需要时使用前向声明

使用当前代码的一种简单方法是简单地不包含link.hin tokens.h,因为struct Linklist或未linklisttoken.h头文件中使用:

#ifndef TOKEN_H
#define TOKEN_H

typedef struct Token{
    char val[30];
}token;

#endif

请注意,上面没有 #include指令。


另一方面,我更改了 header-guard 宏名称,因为所有带有双下划线的符号都在 C 中保留,您不应该自己定义这些符号或名称(作为宏或其他方式)。

这个保留的标识符参考

所有以下划线开头的标识符,后跟大写字母或另一个下划线

[强调我的]


推荐阅读