gpt4 book ai didi

c - 如何引用另一个 C 文件中的变量?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:41 24 4
gpt4 key购买 nike

<分区>

我在名为 list.c 的 C 文件中有一个变量,我使用 main.c 中的函数 initList(void) 初始化该变量。在我的 main.c 中如何获取变量?

主.c:

#include <stdlib.h>
#include "list.h"

int main() {
initList();
return 0;
}

列表.c:

#include "list.h"

listItem *firstItem;
listItem *currentItem;

void initList(void) {
currentItem = calloc(1, sizeof(listItem));
currentItem->data = 0;
currentItem->lastItem = NULL;
currentItem->nextItem = NULL;
firstItem = currentItem;
}
void listInsert(int data) {
listItem *newItem = calloc(1, sizeof(listItem));
newItem->data = data;
newItem->lastItem = currentItem;
newItem->nextItem = NULL;
currentItem = newItem;
}

列表.h:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

void initList(void);
void listInsert(int data);

typedef struct listItem {
void *lastItem;
void *nextItem;
int data;
} listItem;

#endif

如您所见,我在 main.c 文件中调用的 initList(void) 函数中初始化了变量。现在我想用我的变量做点什么。例如,我想用我的函数 listInsert(int data) 将一些东西插入到列表中,但它不起作用。

C 不会保留对我的变量 firstItem 和 currentItem 的引用吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com