I have the following files all in the same directory.
.
├── Makefile
├── lexer.cpp
├── lexer.h
├── parser.cpp
├── parser.h
├── main.cpp
main.cpp depends on parser.h and lexer.h.
lexer.cpp depends on lexer.h
parser.cpp depends on parser.h which in turn depends on lexer.h.
I have a Makefile to compile the files and link them as follows.
all: main
main: main.o lexer.o parser.o
$(CXX) $(CFLAGS) -o $@ mccomp.o lexer.o parser.o
main.o: main.cpp lexer.h parser.h
$(CXX) $(CFLAGS) -c lexer.h parser.h
lexer.o: lexer.cpp lexer.h
$(CXX) $(CFLAGS) -c lexer.h
parser.o: parser.cpp parser.h lexer.h
$(CXX) $(CFLAGS) -c parser.h lexer.h
clean:
rm -rf main
When I execute make I get the following error.
clang-11: error: no such file or directory: 'main.o'
clang-11: error: no such file or directory: 'lexer.o'
clang-11: error: no such file or directory: 'parser.o'
I don’t know why this is happening given that the %.o rules should have generated these files. How do I fix this?
>Solution :
None of the rules for generating .o files actually mention the cpp file they’re supposed to compile. Add the .cpp file (or the magic variable $<) to the recipe instead of all the header files:
main.o: main.cpp lexer.h parser.h
$(CXX) $(CFLAGS) -c main.cpp -o $@
or
main.o: main.cpp lexer.h parser.h
$(CXX) $(CFLAGS) -c $< -o $@
Also note that there is a built-in rule for compiling .cpp files, so it suffices to state the dependencies:
main.o: main.cpp lexer.h parser.h
lexer.o: lexer.cpp lexer.h
parser.o: parser.cpp parser.h lexer.h
Make will then recompile the .o files if one of the input files changes. Note that it uses CXXFLAGS instead of CFLAGS.