簡體   English   中英

main 無法從另一個文件中找到方法

[英]main can't find method from another file

如何使用 main.c 中另一個文件中的方法?

我在我的 list.c 文件中創建了一個方法,並嘗試在我的 main.c 文件中打印出來。 當我嘗試它給我錯誤“當前未聲明,current2 未聲明,頭部未聲明”。

  • 添加 list.h

主.c

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
    
typedef struct list_struct *List;
    
    
int main(){
    
            
createList();
printf("%d %d %d" , head->value, current->value, current2->value);
return 0;
        
        
}
    

列表.c

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
            
typedef struct list_struct *List;
            
struct node {
int value;
struct node *next;
};
            
List createList(){
            
struct node *head = malloc(sizeof(struct node));
                head->value = 45;
                head->next = NULL;
            
struct node *current = malloc(sizeof(struct node));
                current->value = 98;
                current->next = NULL;
                current->next = current;
            
struct node *current2 = malloc(sizeof(struct node));
                current2->value = 3;
                current2->next = NULL;
                return 0;
            
}

列表.h

#ifndef LIST_H_
#define LIST_H_

#ifndef BOOLEAN
    #define BOOLEAN
    typedef enum {false, true} Bool;
#endif
/**
 * Forward pointer declaration to an internal implementation specific hidden list structure.
 */
typedef struct list_struct *List;
/**
 * List life-cycle functions create and delete list or remove a single node with index
 */
List createList();
void deleteList(List head);
List removeAt(List head, int index);

#endif /* LIST_H_ */

main你做

printf("%d %d %d" , head->value, current->value, current2->value);

這意味着headcurrentcurrent2必須可作為來自另一個編譯單元的全局變量。

但是你不這樣做......你將它們定義為createList中的局部變量。

您需要將它們從 function 中移出,例如:

struct node *head;

List createList(){
            
    head = malloc(sizeof(struct node));
    head->value = 45;
    head->next = NULL;

然后在list.h你需要:

extern struct node *head;

currentcurrent2一樣

也就是說...不要使用全局變量...

main中定義變量並將它們作為 arguments 傳遞給 function。

暫無
暫無

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

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