Home > Mobile >  Getting 'undefined reference to' function although I have clearly included the files
Getting 'undefined reference to' function although I have clearly included the files

Time:11-18

I have 3 files:

main.c

#include "fle.h"

int main(int argc, char **argv) {
     FILE *fptr = checkFile(argv[1]);
}

fle.c

#include "fle.h"

FILE *checkFile(char *path)
{
 ...
}

fle.h

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

#ifndef FLE_H_
#define FLE_H_

FILE *checkFile(char *path);

#endif

My makefile looks like this

CC = gcc
CFLAGS  = -g -Wall
TARGET = main

all: $(TARGET)

$(TARGET): $(TARGET).c
    $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c

clean:
    $(RM) $(TARGET)

As a minimal (non)working example, it throws an error

/main.c:4: undefined reference to `checkFile'

I'm curious why the checkFile function is surrounded by backtick from the left and apostrophe from the right, it doesn't seem right, but I don't think that's the problem.

I'd appreciate any help regarding this issue, it might be something trivial, but clearly I'm not skilled enough to resolve it myself.

EDIT: I have renamed the names from file to fle everywhere to prevent some collisions with the system libraries, but it didn't change a thing.

CodePudding user response:

While you include the declaration you need to link in the definition. The easiest thing is to change the Makefile as follows:

CC = gcc
CFLAGS  = -g -Wall
TARGET = main

all: $(TARGET)

$(TARGET): $(TARGET).c fle.c

clean:
    rm -f $(TARGET)
  •  Tags:  
  • c
  • Related