简体   繁体   English

main 无法从另一个文件中找到方法

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

How can I use a method from another file in main.c?如何使用 main.c 中另一个文件中的方法?

I created a method in my list.c file and try to print it out in my main.c file.我在我的 list.c 文件中创建了一个方法,并尝试在我的 main.c 文件中打印出来。 When I try that it gives me the error "current undeclared,current2 undeclared,head undeclared".当我尝试它给我错误“当前未声明,current2 未声明,头部未声明”。

  • added list.h添加 list.h

Main.c主.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;
        
        
}
    

list.c列表.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;
            
}

list.h列表.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_ */

In main you do main你做

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

which means that head , current and current2 must be available as global variables from another compilation unit.这意味着headcurrentcurrent2必须可作为来自另一个编译单元的全局变量。

But you don't do that... you define them as local variables inside createList .但是你不这样做......你将它们定义为createList中的局部变量。

You need to move them out of the function like:您需要将它们从 function 中移出,例如:

struct node *head;

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

and then in list.h you need:然后在list.h你需要:

extern struct node *head;

And the same for current and current2currentcurrent2一样

That said... Don't use globals...也就是说...不要使用全局变量...

Define the variables in main and pass them as arguments to the function.main中定义变量并将它们作为 arguments 传递给 function。

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

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