0

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

1
  • You don't have a global array. You need to create one if you want to use it in one module, let alone multiple modules. Commented Oct 23, 2014 at 0:53

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your help, I'm still getting the error message after making all of those changes. is the prototype just a line in the header file like so? int readPrograms();
@user3192682 Yes, that's the prototype. What errors do you get after making the changes?
the same error that I was receiving originally, it is posted above
@user3192682 I just tried compiling this, it compiles perfectly. I made exactly the four changes that I described in the answer, and compiled the code like this: gcc main.c fileReader.c. I got a.out which reads from files.txt, and prints the first four strings.
@user3192682 Here is a pastebin with your code. Comments show the names of files. I think you missed step #3, adding a definition. It's on line 23 of the pastebin.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.