Search code examples
compiler-constructionmakefile

-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?


Solution

  • 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)