user1542422
user1542422

Reputation: 319

"undefined reference to function" error on a function in the library

I am trying to work with id3 tags with C, so I downloaded mplib and installed it.

I am trying to call this function inside mplib.h where __P is a Macro

extern id3_tag_list* mp_get_tag_list_from_file __P((const char* path));

by writing in example.c:

int main() {
    char* pa = "R U MINE";
    id3_tag_list* list = mp_get_tag_list_from_file(pa);
    id3_tag *newTag = list->tag;
    printf("tag %d\n", newTag->version);
    return 0;
}

but when I link, I get an error:

example.o: In function `main':
example.c:(.text+0x27): undefined reference to `mp_get_tag_list_from_file'
collect2: error: ld returned 1 exit status
make: *** [example] Error 1

My makefile looks like this

OBJECTS = example.o
target=example
misc=Makefile
cflags=-Wall -g -O0 -Werror -pedantic -std=c99

all: $(target)

$(target) : $(OBJECTS) $(misc)
    gcc $(cflags) -o $(target) $(OBJECTS)

clean:
    rm -f $(OBJECTS) $(target)

I am having trouble compiling this. I believe the problem is that I am having issues with linking it to the actual mplib.c file where that function is actually defined, but I am not sure how to do it exactly. I got the library from http://mplib.sourceforge.net/ and I installed it by using 'make' and 'make install'. Am I supposed to manually move the mplib.c file somewhere?

Upvotes: 0

Views: 779

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

If you build mplib 1.0.3, it creates a library libmp.a. Therefore, you need to specify -lmp on the linker command line, and perhaps -L /where/you/installed/it/lib to specify the directory where the library was installed.


The linker command line should probably look like:

LDFLAGS = -L/usr/local/lib
LDLIBS  = -lmp

gcc $(cflags) -o $(target) $(OBJECTS) $(LDFLAGS) $(LDLIBS)

Actually, it would be better if it looked like:

$(CC) $(CFLAGS) -o $@ $(OBJECTS) $(LDFLAGS) $(LDLIBS)

The upper-case macro CFLAGS is used for flags to the C compiler. $@ means 'the name of the current target'. LDFLAGS are flags for the linker, such as where to find libraries, and LDLIBS contains the specification of libraries. An option such as -lmp means 'look for libmp.so or libmp.a in each of the directories on the list of places searched for libraries' (to a sufficiently close approximation). The -L option prefixes the following directory to the list of places searched for libraries.

Upvotes: 1

Related Questions