Nathan
Nathan

Reputation: 21

How to fix 'undefined reference' when compiling in C?

I'm trying to compile a C program linking two previously created object files but keep getting an 'undefined reference' error.

I'm using Visual Code to write the code and Ubuntu on Windows to compile using a makefile. The two C files, task5.c and reverse.c which have been made into object files both contain #include reverse.h statements which contains the prototypes for the functions in reverse.c.

task5.c

#include <stdio.h>
#include "ctap.h"
#include "reverse.h"

TESTS {
    const char *a = "Family";
    char *b = reverse(a);

    //test 1
    ok(string_length(a) == string_length(b), "Strings are the same size");

    //test 2
    is("ylimaF", b, "Strings match");
}

reverse.c

#include <stdio.h>
#include <stdlib.h>
#include "reverse.h"

char *reverse(const char *str) {
    //code
}

int string_length(const char *str) {
    //code
}

reverse.h

char *reverse(const char *str);
int string_length(const char *str);

makefile

linked:
    gcc -o linked task5.o reverse.o

task5.o
    gcc -c -o task5.o task5.c

reverse.o
    gcc -c -o reverse.o reverse.c

When I run the command make linked I expect it to be made and return nothing.

But when I run that command I get this error:

cc   task5.o   -o linked
task5.o: In function `ctap_tests':
task5.c:(.text+0x1abe): undefined reference to `reverse'
task5.c:(.text+0x1ace): undefined reference to `string_length'
task5.c:(.text+0x1adc): undefined reference to `string_length'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'linked' failed
make: *** [task5] Error 1

Upvotes: 1

Views: 1446

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409432

According to this GNU make documentation, the GNU make program will try to use GNUMakefile, makefile or Makefile.

The make program will not try makefile.mk, which means that e.g. make linked will use no makefile and only the default rules.

You can solve this by either renaming your makefile as Makefile (the most common) or makefile; Or by using the -f option to specify the makefile

$ make -f makefile.mk linked

Upvotes: 1

Related Questions