Martin Perry
Martin Perry

Reputation: 9527

C++ makefile - linker not find external lib

I have a makefile that successfully build *.obj files. After I reach the linking part, I have a lot of error to undefined reference.

CC = g++

INCLUDE_DIRS = -I/usr/include/freetype2/ -I../MyLibs/ \
               -I../MyLibs/svg/

LIB_DIRS = -L./ -L../MyLibs/ -L/usr/lib64/ -L/usr/lib64/mysql/

LIBS = -lMyUtils -lfreetype  -lmysqlclient -lsqlite3 


CFLAGS = -std=c++11 -lm -lpthread -lstdc++ -ldl  -Wall -O2 \
         $(INCLUDE_DIRS)

OBJ = *** list of obj files ***

BIN = my_program

$(BIN): $(OBJ) $(OBJ)
    $(CC) $(CFLAGS) $(LIB_DIRS) $(LIBS) $^ -o $@

I am unable to see what can be wrong. MyUtils is static library, that I have also build using different makefile (If I look inside with ar, I see all obj present). Also, I have used the same library to build another project (dynamic library) and build was correctly finished.

A am using gcc 4.7.2 under CentOS 6.5.

Upvotes: 0

Views: 189

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61327

Your linker recipe places the libraries before the object files that require them. The linker will only examine a library to resolve undefined references it already noted in previously linked objects, so if you place all the libraries before all the object files then none of libraries are examined and all of the calls to those libraries in the object files end up undefined.

Rewrite e.g as:

$(BIN): $(OBJ)
    $(CC) $(CFLAGS) $^ $(LIB_DIRS) $(LIBS) -o $@

(And no need to duplicate the $(OBJ) prerequisities)

Upvotes: 4

Related Questions