gpt4 book ai didi

c - 将变量从 main 共享到另一个 c 文件

转载 作者:行者123 更新时间:2023-11-30 19:12:12 25 4
gpt4 key购买 nike

我有一个函数

int InsertToList(List **head,......,char *FileName);

而这个函数是在Source1.c中实现的

但是,此 FileName 字符串是从命令行参数获取的,并在同一项目的 Main.c 的主函数内声明

我想知道如何在 InsertToList 函数中拥有 FileName 字符串而不将其传递给其参数并且也不使用全局变量?

我的意思是:

int InsertToList(List **head,......)
{
File *fp;
fp = fopen(FileName,"r"); // here FileName is passed from the main in Main.c
doSomething();
}

最佳答案

And i was wondering how can i have the FileName string in InsertToList function without passing it to its arguments and also without using global variables.

  1. main.c 中创建一个文件范围的 static 变量。
  2. main.c 中设置值。
  3. main.c 中提供一个函数来返回该值。
  4. 使用 InsertToList 中的函数。
<小时/>

main.c

static char* fileName;
char* getFileName()
{
return fileName;
}

int main(int argc, char** argv)
{
fileName = ...;
}

来源1.c:

// Provide a declaration of the function that's defined in main.c.
char* getFileName();

int InsertToList(List **head,...)
{
File *fp;
fp = fopen(getFileName(),"r");
}

关于c - 将变量从 main 共享到另一个 c 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37621440/

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