Search code examples
carraysheader-filesextern

How to use a global array in multiple modules


I'm trying to access the programs array in my main file. It is declared in the header file and initialized in a separate module called fileReader. The error message I receive is

Undefined symbols for architecture x86_64: "_programs", referenced from: _main in test-0bf1e8.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

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[];

Thanks in advance


Solution

  • You are not supposed to include C files from other C files, only the header files.

    Here is what you need to fix:

    • Add a prototype of readPrograms function to the header.h
    • Remove #include "fileReader.c" from the main.c file
    • Add a definition of programs array to one of your C files (say, main.c).
    • Remove declaration of the local programs from readPrograms

    The definition of programs that you put in main.c should look like this:

    char* programs[50];
    

    You can put it before or after your main() function.