簡體   English   中英

為什么使用 struct 有效而 typedef struct 無效?

[英]Why does using struct work but typedef struct not?

我的代碼有問題。

這是我的演示:

我的文件結構是

├── 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.htokens.h ,因為struct Linklistlinklist未在使用token.h頭文件:

#ifndef TOKEN_H
#define TOKEN_H

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

#endif

請注意,上面沒有#include指令。


在另一個注釋中,我更改了 header-guard 宏名稱,因為所有帶有雙下划線的符號在 C 中都是保留的,您不應該自己定義這些符號或名稱(作為宏或其他)。

這個保留的標識符參考

所有以下划線開頭的標識符,后跟大寫字母或另一個下划線

[強調我的]

發生這種情況是因為您通過在 token.h 中包含 link.h 創建了circular dependency項,反之亦然。

如果您從 token.h 中刪除#include <link.h> ,一切都應該正常工作。

當您在主文件中 #include token.h 時,將會發生以下情況:

#ifndef __TOKEN_H__ //not defined
#define __TOKEN_H__
#include <stdio.h>
//#include "link.h" expands to:

  #ifndef __LINKLIST_H__ //not defined
  #define __LINKLIST_H__
  #include <stdio.h>
  //#include "token.h" expands to:

    #ifndef __TOKEN_H__ //defined
    #endif

  typedef struct Linklist{
      token* elem;          // token was not declared yet: ERROR
      struct Linklist *next;  
  }linklist;

  #endif 

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

#endif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM