我正在尝试访问主文件中的程序数组。它在头文件中声明并在名为 fileReader 的单独模块中初始化。我收到的错误消息是
体系结构 x86_64 的 undefined symbol : “_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;
}
文件读取器.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;
}
标题.h
extern char* programs[];
提前致谢
最佳答案
您不应该包含其他 C 文件中的 C 文件,而只能包含头文件。
以下是您需要修复的问题:
- 将
readPrograms
函数的原型(prototype)添加到header.h
- 从 main.c 文件中删除
#include "fileReader.c"
- 将
programs
数组的定义添加到您的 C 文件之一(例如 main.c)。 - 从
readPrograms
中删除本地程序
的声明
放入 main.c 中的程序
的定义应如下所示:
char* programs[50];
您可以将其放在 main()
函数之前或之后。
关于c - 如何在多个模块中使用全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26519542/