简体   繁体   中英

how to include and compile a library in a makefile

I'm trying to build this hello world project that includes a library with both .h and .cpp files (and hence the library needs to be compiled too). The directory structure is

helloworld/lib/StanfordCPPLib/console.h
          /src/hello.h
          /src/hello.cpp

You can see the project code here

When I run make with the following makefile, i get an error that console.h (which is included by hello.cpp ) cannot be found

CC=gcc
CFLAGS=-I.

DEPS = hello.h
OBJ = hello.o

#console.h is in lib/StanfordCPPLib and it is included by hello.cpp
INC=-I../lib/StanfordCPPLib

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS) 

hellomake: $(OBJ)
    g++ -o $@ $^ $(CFLAGS) $(INC)

How to include the StanfordLibrary in this makefile so that it is both included and compiled.

(note, I'm aware the original sourcecode contains a QT creator file, however, I'm trying to build it using make)

The main problem is that your rule for building objs:

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

doesn't use your include path in $(INC)

Another problem is that you are matching on the wrong file extension. eg %.c should be %.cpp .

You also have some extra redundant junk in there, so I suggest you update your makefile like this to get the idea:

CC=gcc

DEPS = hello.h
OBJ = hello.o
INC=-I. -I../lib/StanfordCPPLib

%.o: %.cpp $(DEPS)
    $(CC) $(INC) -c $<

hellomake: $(OBJ)
    g++ -o $@ $^

This builds fine in my little mock setup. Remember that it is actually necessary for you to use g++ under hellomake: for everything to link properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM