【问题标题】:How to use a global array in multiple modules如何在多个模块中使用全局数组
【发布时间】:2014-10-23 00:49:17
【问题描述】:

我正在尝试访问我的主文件中的程序数组。它在头文件中声明并在名为 fileReader 的单独模块中初始化。我收到的错误信息是

架构 x86_64 的未定义符号: “_programs”,引用自: _main 在 test-0bf1e8.o ld:未找到架构 x86_64 的符号 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"
#include "fileReader.c"

int main() {

    readPrograms();
    for (int i=0; i<4; i++) {
        printf("%s", programs[i]);
    } 

    return 0;
}

fileReader.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"

int readPrograms() {
    int i=0;
    int numProgs=0;
    char* programs[50];
    char line[50];

    FILE *file;
    file = fopen("files.txt", "r");

    while(fgets(line, sizeof(line), file)!=NULL) {
        //add each filename into array of programs
        programs[i]=strdup(line); 
        i++;
    }

    fclose(file);

    return 0;
}

header.h

extern char* programs[];

提前致谢

【问题讨论】:

  • 您没有全局数组。如果你想在一个模块中使用它,你需要创建一个,更不用说多个模块了。

标签: c arrays header-files extern


【解决方案1】:

您不应该包含来自其他 C 文件的 C 文件,只能包含头文件。

这是您需要解决的问题:

  • readPrograms函数的原型添加到header.h
  • 从 main.c 文件中删除 #include "fileReader.c"
  • programs 数组的定义添加到您的一个 C 文件(例如 main.c)中。
  • readPrograms 中删除本地programs 的声明

你在 main.c 中对programs 的定义应该是这样的:

char* programs[50];

您可以将它放在 main() 函数之前或之后。

【讨论】:

  • 感谢您的帮助,在进行所有这些更改后,我仍然收到错误消息。原型只是头文件中的一行吗? int readPrograms();
  • @user3192682 是的,这就是原型。进行更改后会出现什么错误?
  • 和我原来收到的一样的错误,贴在上面
  • @user3192682 我刚刚尝试编译它,它编译完美。我做了我在答案中描述的四个更改,并编译了这样的代码:gcc main.c fileReader.c。我得到了从files.txt 读取的a.out,并打印了前四个字符串。
  • @user3192682 这是带有您的代码的pastebin。注释显示文件的名称。我认为您错过了第 3 步,即添加定义。它在 pastebin 的第 23 行。
猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多