Search code examples
cgcclinker-errors

How to fix unresolved reference error in my C program


I have just learnt about multi-file compilation in C and tried out a test question, but I keep getting the same error while compiling even after following all instructions. My program takes the response of a student to a test in the form of a array (this is done for each student in a separate .c file) and then matches it with the answer key which is declared in the main file. I have defined a function answer() which takes the question number as a parameter and returns the student's response to that question.

The code in each file is as follows

main file (checkanswer.c)

#include <stdio.h>
#include "answer.h"

int main()
{
    int anskey[4]={5,10,0,4}, score=0;
    for (int i=0;i<3;i++)
    {
        if (anskey[i]==answer(i+1))
        {
            score+=1;
        }
    }
    printf("The score of student is %d",score);
}

student1.c

#include "answer.h"

int answer(int qno)
{
    int ans[4] = {15,10,2,4};
    return ans[qno-1];
}

answer.h

int answer(int qno);

To do the multi-file compilation, I followed the instructions and generated .o files from both .c files using the -c flag and then used -o to compile and give the executable.

I ran the following in terminal

gcc -c checkanswer.c
gcc -c student1.c
gcc -o student1.o checkanswer.o
./a.out

And this gives me an error stating "unresolved reference to answer"

Also, I tried using

gcc checkanswer.c student1.c

Which worked as intended.

So can someone shed some light as to what is wrong with my code and what made the second method work.


Solution

  • First: GCC's -o stand for "output", it's the output file's name From the man gcc:

    -o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.

    If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output.

    You should get rid of this error by runninh gcc -o NAME student1.o checkanswer.o (you can replace NAME by a.out or my_program)

    GCC's -c create an object file (.o) that is somewhat a compiled version of your .c file.