Renjith
Renjith

Reputation: 417

-I flag not working in make file

I just wrote simple make file to compile any number of files. When I add -I flag to add include directory, its not working.

    CC=g++
    CFLAGS=-I./inc
    DEPS = add.h mul.h
    OBJ = main.o add.o mul.o 

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

    main: $(OBJ)
        $(CC) -o $@ $^ $(CFLAGS)

following is the out put when I executed make. You can see -I./inc is missing

    ~/PGMS/testMakeFile > make
    g++    -c -o main.o main.cc
    main.cc:1:17: fatal error: add.h: No such file or directory

I already wasted long time to resolve this, can someone help me to resolve this?

Upvotes: 1

Views: 2610

Answers (2)

Chnossos
Chnossos

Reputation: 10486

The rule you've written to handle .o files is never called because it builds from %.c files instead of %.cc files. Thus, make's implicit rule for .cc files is called with $(CXX) and $(CXXFLAGS) C++ variables.

Change CFLAGS=-I./inc to CXXFLAGS += -I./inc and it should work.


All that said, the -I flag is a preprocessor flag, meaning you should actually be using the CPPFLAGS variable instead (and it will continue to work as expected since both CXXFLAGS and CPPFLAGS are implicitly used).

Your makefile can thus be simplified:

OBJ := main.o add.o mul.o
DEP := add.h mul.h

CPPFLAGS := -Iinc

main: $(OBJ)
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

$(OBJ): $(DEP)

Upvotes: 5

jeffrey_t_b
jeffrey_t_b

Reputation: 1769

It doesn't look like you have a rule for .cc files (notice that your custom rule is to convert .c files into .o files).

Note that in gnu make (at least), the default c++ rule (i.e. for .cc files) uses the CXXFLAGS variable by default. See the GNU make

Upvotes: 0

Related Questions