I have some limited knowledge of GNU makefile that has failed me at the moment.
I have a class declaration file: mdfTree.h, an implementation of the class mdfTree.cpp, and a mdfTree_x.cpp file with a main where I create an object of class mdfTree and call its public functions, which in turn call some private member variables of mdfTree.
I am compiling it with the Makefile:
CXX=g++
CXXFLAGS=-g -Wall -W -Wconversion -Wshadow -Wcast-qual -Wwrite-strings $(shell root-config --cflags --gl\
ibs)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
mdfTree_x: mdfTree_x.o
g++ $(LDFLAGS) -o mdfTree_x mdfTree_x.o $(LDLIBS)
mdfTree_x.o: mdfTree_x.cpp
g++ $(LDFLAGS) $(CXXFLAGS) -c mdfTree_x.cpp
mdfTree.cpp and mdfTree_x.cpp has an #include mdfTree.h in it. Does mdfTree_x.cpp need #include mdfTree.cpp as well?
I think my Makefile is wrong because a public function from class mdfTree can’t see a private variable of the same class, when I try to compile. Also, when I insert a syntax error into mdfTree.h, then the compiler doesn’t pick it up. How do I tell Makefile that mdfTree_x needs to use/compile mdfTree.h/.cpp?
You’ll need to explicitly add all of the dependancies, in this case your executable depends on mdfTree.o having been built and mdfTree.o and mdfTree_x.o depend on mdfTree.h. Your dependancies should be like
Some compilers (e.g. gnu & intel) are able to automatically list header dependancies in make format. For example this makefile will regenerate the executable when any of
mdfTree_x.cpp,mdfTree.cppormdfTree.his changed:The CPPFLAGS will create a .d file with header dependancies when compiling, the -include line will try to include these into the makefile if present (if they’re not present the source file is going to be recompiled anyway, so extra dependancies don’t matter). The contents of the .d file will be something like
Also, you don’t need to explicitly write make rules in most cases – for instance if you have a file
foo.olisted as a dependancy gnu make’s default rules are to run(and similar for other languages). Similarly linking is automatic if the executable name matches one of the object files, e.g.
will run (note CC not CXX)
Using the default rules keeps makefiles simpler, and also lets you use environment variables to set up a default compiler.