c - 为什么使用 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));
我想问为什么会出现这种情况?
解决方案
你有一个循环包含依赖,你需要打破这个循环。
常见的方法是停止在头文件中包含不需要的文件,并在需要时使用前向声明。
使用当前代码的一种简单方法是简单地不包含link.h
in tokens.h
,因为struct Linklist
或未linklist
在token.h
头文件中使用:
#ifndef TOKEN_H
#define TOKEN_H
typedef struct Token{
char val[30];
}token;
#endif
请注意,上面没有 #include
指令。
另一方面,我更改了 header-guard 宏名称,因为所有带有双下划线的符号都在 C 中保留,您不应该自己定义这些符号或名称(作为宏或其他方式)。
所有以下划线开头的标识符,后跟大写字母或另一个下划线
[强调我的]
推荐阅读
- r - 使用函数 clusterR 的并行化过程出错:集群错误
- java - 如何在 Spring 上测试 CSRF 保护?
- sql - HIVE 布尔过滤器
- python - 如何在 Django REST 框架中为多对多字段定义“IsOwner”自定义权限?
- github - 将代码从 GitHub 复制到 GitLab - 代码被复制到不同的位置
- python - Python Keras CNN 模型与 C# 后端项目的通信
- reactjs - TypeError:无法读取未定义的属性“exec”(样式有问题)
- javascript - 世博会视频未加载动态 URI
- html - 如何使日文字体(Ipaex gothic / mincho)加粗?
- sql - 使用循环中的现有表更新数据