Why does GNU make always re-link my project? - c++

I have the following Makefile in a directory full of .cpp and .h files:
CFLAGS=-g -std=c++0x -Wall -pedantic -Wextra -D __STDC_LIMIT_MACROS -D __STDC_FORMAT_MACROS -O0
CXX=g++
LDFLAGS=-lgmp -lmathsat -lz3
all: Foo.o Bar.o
$(CXX) $(CFLAGS) -o myexe Foo.o Bar.o $(LDFLAGS)
depend: .depend
.depend: $(wildcard *.cpp)
rm -f ./.depend
$(CXX) $(CFLAGS) -MM $^ > ./.depend
include .depend
%.o: %.cpp
$(CXX) $(CFLAGS) $(INCLUDE) $< -c
clean:
rm -f *.o myexe
When I hit make, it invariably executes the last step (linking) even when none of the .o files have changed. How can I prevent make from doing that? I'd expect make to output Everything up-to-date or something similar.
I'm on a i686 GNU/Linux machine with GNU Make 3.82 and g++ version 4.8.2.

Make relinks your project because it tries to build all. The rule for all does not create any file named all. Instead it produces myexe. Next time you run make, it will see that there's no all, but there's a rule to build one, so it dutifully executes that rule which happens to link myexe every time you run make.
In order to fix your problem you need to change your makefile to look roughly like this:
all: myexe
echo Build done
myexe: <myexe dependencies go here>
$(CXX) $(CFLAGS) -o myexe $(wildcard *.o) $(LDFLAGS)

Make always tries to build the top rule. For you, this is all. Since your all rule doesn't actually make an all file it will always be run.
Your probably want your all rule to be a myexe rule and, if you want an explicit all rule, have a dependency only rule: all: myexe.
(With GNU Make, you might want to explicitly declare those targets which aren't supposed to generate a real file with a .PHONY rule. e.g. .PHONY: all depend clean.)

make is a rule-based expert system.
You give it a heap of rules and a target (default target is the first one listed), and then it builds a complete dependency tree.
All parts are rebuilt iff they are non-existent resp. older than their dependencies, recursively.
The rule you are stumbling over is this: Because the target all does not create an output file all, make invokes the non-existent-or-outdated rule.
You can correct this by making the target all not do any work but instead just depend on the output file. Marking it .PHONY is also a good idea.

Related

How to make a .exe that gives the compiler commands [duplicate]

We are required to use a Makefile to pull everything together for our project, but our professor never showed us how to.
I only have one file, a3driver.cpp. The driver imports a class from a location, "/user/cse232/Examples/example32.sequence.cpp".
That's it. Everything else is contained with the .cpp.
How would I go about making a simple Makefile that creates an executable called a3a.exe?
Since this is for Unix, the executables don't have any extensions.
One thing to note is that root-config is a utility which provides the right compilation and linking flags; and the right libraries for building applications against root. That's just a detail related to the original audience for this document.
Make Me Baby
or You Never Forget The First Time You Got Made
An introductory discussion of make, and how to write a simple makefile
What is Make? And Why Should I Care?
The tool called Make is a build dependency manager. That is, it takes care of knowing what commands need to be executed in what order to take your software project from a collection of source files, object files, libraries, headers, etc., etc.---some of which may have changed recently---and turning them into a correct up-to-date version of the program.
Actually, you can use Make for other things too, but I'm not going to talk about that.
A Trivial Makefile
Suppose that you have a directory containing: tool tool.cc tool.o support.cc support.hh, and support.o which depend on root and are supposed to be compiled into a program called tool, and suppose that you've been hacking on the source files (which means the existing tool is now out of date) and want to compile the program.
To do this yourself you could
Check if either support.cc or support.hh is newer than support.o, and if so run a command like
g++ -g -c -pthread -I/sw/include/root support.cc
Check if either support.hh or tool.cc are newer than tool.o, and if so run a command like
g++ -g -c -pthread -I/sw/include/root tool.cc
Check if tool.o is newer than tool, and if so run a command like
g++ -g tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
Phew! What a hassle! There is a lot to remember and several chances to make mistakes. (BTW-- the particulars of the command lines exhibited here depend on our software environment. These ones work on my computer.)
Of course, you could just run all three commands every time. That would work, but it doesn't scale well to a substantial piece of software (like DOGS which takes more than 15 minutes to compile from the ground up on my MacBook).
Instead you could write a file called makefile like this:
tool: tool.o support.o
g++ -g -o tool tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
tool.o: tool.cc support.hh
g++ -g -c -pthread -I/sw/include/root tool.cc
support.o: support.hh support.cc
g++ -g -c -pthread -I/sw/include/root support.cc
and just type make at the command line. Which will perform the three steps shown above automatically.
The unindented lines here have the form "target: dependencies" and tell Make that the associated commands (indented lines) should be run if any of the dependencies are newer than the target. That is, the dependency lines describe the logic of what needs to be rebuilt to accommodate changes in various files. If support.cc changes that means that support.o must be rebuilt, but tool.o can be left alone. When support.o changes tool must be rebuilt.
The commands associated with each dependency line are set off with a tab (see below) should modify the target (or at least touch it to update the modification time).
Variables, Built In Rules, and Other Goodies
At this point, our makefile is simply remembering the work that needs doing, but we still had to figure out and type each and every needed command in its entirety. It does not have to be that way: Make is a powerful language with variables, text manipulation functions, and a whole slew of built-in rules which can make this much easier for us.
Make Variables
The syntax for accessing a make variable is $(VAR).
The syntax for assigning to a Make variable is: VAR = A text value of some kind
(or VAR := A different text value but ignore this for the moment).
You can use variables in rules like this improved version of our makefile:
CPPFLAGS=-g -pthread -I/sw/include/root
LDFLAGS=-g
LDLIBS=-L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz \
-Wl,-framework,CoreServices -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root \
-lm -ldl
tool: tool.o support.o
g++ $(LDFLAGS) -o tool tool.o support.o $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is a little more readable, but still requires a lot of typing
Make Functions
GNU make supports a variety of functions for accessing information from the filesystem or other commands on the system. In this case we are interested in $(shell ...) which expands to the output of the argument(s), and $(subst opat,npat,text) which replaces all instances of opat with npat in text.
Taking advantage of this gives us:
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
tool: $(OBJS)
g++ $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is easier to type and much more readable.
Notice that
We are still stating explicitly the dependencies for each object file and the final executable
We've had to explicitly type the compilation rule for both source files
Implicit and Pattern Rules
We would generally expect that all C++ source files should be treated the same way, and Make provides three ways to state this:
suffix rules (considered obsolete in GNU make, but kept for backwards compatibility)
implicit rules
pattern rules
Implicit rules are built in, and a few will be discussed below. Pattern rules are specified in a form like
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
which means that object files are generated from C source files by running the command shown, where the "automatic" variable $< expands to the name of the first dependency.
Built-in Rules
Make has a whole host of built-in rules that mean that very often, a project can be compile by a very simple makefile, indeed.
The GNU make built in rule for C source files is the one exhibited above. Similarly we create object files from C++ source files with a rule like $(CXX) -c $(CPPFLAGS) $(CFLAGS).
Single object files are linked using $(LD) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS), but this won't work in our case, because we want to link multiple object files.
Variables Used By Built-in Rules
The built-in rules use a set of standard variables that allow you to specify local environment information (like where to find the ROOT include files) without re-writing all the rules. The ones most likely to be interesting to us are:
CC -- the C compiler to use
CXX -- the C++ compiler to use
LD -- the linker to use
CFLAGS -- compilation flag for C source files
CXXFLAGS -- compilation flags for C++ source files
CPPFLAGS -- flags for the c-preprocessor (typically include file paths and symbols defined on the command line), used by C and C++
LDFLAGS -- linker flags
LDLIBS -- libraries to link
A Basic Makefile
By taking advantage of the built-in rules we can simplify our makefile to:
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
support.o: support.hh support.cc
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) tool
We have also added several standard targets that perform special actions (like cleaning up the source directory).
Note that when make is invoked without an argument, it uses the first target found in the file (in this case all), but you can also name the target to get which is what makes make clean remove the object files in this case.
We still have all the dependencies hard-coded.
Some Mysterious Improvements
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
depend: .depend
.depend: $(SRCS)
$(RM) ./.depend
$(CXX) $(CPPFLAGS) -MM $^>>./.depend;
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) *~ .depend
include .depend
Notice that
There are no longer any dependency lines for the source files!?!
There is some strange magic related to .depend and depend
If you do make then ls -A you see a file named .depend which contains things that look like make dependency lines
Other Reading
GNU make manual
Recursive Make Considered Harmful on a common way of writing makefiles that is less than optimal, and how to avoid it.
Know Bugs and Historical Notes
The input language for Make is whitespace sensitive. In particular, the action lines following dependencies must start with a tab. But a series of spaces can look the same (and indeed there are editors that will silently convert tabs to spaces or vice versa), which results in a Make file that looks right and still doesn't work. This was identified as a bug early on, but (the story goes) it was not fixed, because there were already 10 users.
(This was copied from a wiki post I wrote for physics graduate students.)
I've always thought this was easier to learn with a detailed example, so here's how I think of makefiles. For each section you have one line that's not indented and it shows the name of the section followed by dependencies. The dependencies can be either other sections (which will be run before the current section) or files (which if updated will cause the current section to be run again next time you run make).
Here's a quick example (keep in mind that I'm using 4 spaces where I should be using a tab, Stack Overflow won't let me use tabs):
a3driver: a3driver.o
g++ -o a3driver a3driver.o
a3driver.o: a3driver.cpp
g++ -c a3driver.cpp
When you type make, it will choose the first section (a3driver). a3driver depends on a3driver.o, so it will go to that section. a3driver.o depends on a3driver.cpp, so it will only run if a3driver.cpp has changed since it was last run. Assuming it has (or has never been run), it will compile a3driver.cpp to a .o file, then go back to a3driver and compile the final executable.
Since there's only one file, it could even be reduced to:
a3driver: a3driver.cpp
g++ -o a3driver a3driver.cpp
The reason I showed the first example is that it shows the power of makefiles. If you need to compile another file, you can just add another section. Here's an example with a secondFile.cpp (which loads in a header named secondFile.h):
a3driver: a3driver.o secondFile.o
g++ -o a3driver a3driver.o secondFile.o
a3driver.o: a3driver.cpp
g++ -c a3driver.cpp
secondFile.o: secondFile.cpp secondFile.h
g++ -c secondFile.cpp
This way if you change something in secondFile.cpp or secondFile.h and recompile, it will only recompile secondFile.cpp (not a3driver.cpp). Or alternately, if you change something in a3driver.cpp, it won't recompile secondFile.cpp.
Let me know if you have any questions about it.
It's also traditional to include a section named "all" and a section named "clean". "all" will usually build all of the executables, and "clean" will remove "build artifacts" like .o files and the executables:
all: a3driver ;
clean:
# -f so this will succeed even if the files don't exist
rm -f a3driver a3driver.o
EDIT: I didn't notice you're on Windows. I think the only difference is changing the -o a3driver to -o a3driver.exe.
Why does everyone like to list out source files? A simple find command can take care of that easily.
Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...
appname := myapp
CXX := clang++
CXXFLAGS := -std=c++11
srcfiles := $(shell find . -name "*.C")
objects := $(patsubst %.C, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
You had two options.
Option 1: simplest makefile = NO MAKEFILE.
Rename "a3driver.cpp" to "a3a.cpp", and then on the command line write:
nmake a3a.exe
And that's it. If you're using GNU Make, use "make" or "gmake" or whatever.
Option 2: a 2-line makefile.
a3a.exe: a3driver.obj
link /out:a3a.exe a3driver.obj
I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.
appname := myapp
CXX := g++
CXXFLAGS := -Wall -g
srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.
Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this (note that the indent must be a TAB):
main_target : source1 source2 etc
command to build main_target from sources
source1 : dependents for source1
command to build source1
There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them.
So your makefile will look something like this.
a3a.exe : a3driver.obj
link /out:a3a.exe a3driver.obj
a3driver.obj : a3driver.cpp
cc a3driver.cpp
I suggest (note that the indent is a TAB):
tool: tool.o file1.o file2.o
$(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $#
or
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o
The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).
Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).
Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.
Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:
CFLAGS = -Wall
LDLIBS = -lm
One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:
CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)
The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:
override CPPFLAGS += -MMD
include $(wildcard *.d)
-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.
For sure, a well written Makefile should also include clean and distclean rules:
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.
The all rule is also appreciated. In order to work, it should be the first rule of your file:
all: tool
You may also add an install rule:
PREFIX = /usr/local
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin
DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.
One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).
So to summarise, your full Makefile should look like:
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)
all: tool
tool: tool.o file1.o file2.o
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin

Using makefile arguments without foo=

I have a makefile I use to compile a single file. When I need to pass an argument, I use target=targetFile.
The script takes the argument, looks for the file (within the same directory) that has the same value as the argument and compiles it.
I use this for compiling problems from uhunt and uva, which use a single c++ file. So I dont' need multiple makefiles for multiple source files. Single makefile for multiple source files is the reason I made the makefile.
Here's the code I have so far
OBJS = $(target).o
CC = g++
CFLAGS = -Wall -g -std=c++11
INCLUDE = -I./$(target)
#default command to run
all : Main-$(target) clean run
#compile and build
Main-$(target) : $(OBJS)
$(CC) $(CFLAGS) $^ -o $#
%.o : %.cpp
$(CC) -c $(CFLAGS) $<
#remove object and any other garbage files.
clean:
rm -rf -d $(target).o *~ *% *# .#*
#remove the compiled file
clean-all:
$(clean) rm Main-$(target)
#run the compiled file
run:
./Main-$(target)
The command I use to compile is,
make target=sourceFile
Also I don't include the file extension, I have all my source file extensions to be cpp
What I want in the end is:
make sourceFile
Just a side note, for using the command clean and clean-all, I use
make target=sourceFile clean
make target=sourceFile clean-all
I'd prefer if I can use:
make sourceFile clean
make sourceFile clean-all
You may use common Makefile variable MAKECMDGOALS that contains all targets passed to make.
Please try this variant
CC = g++
CFLAGS = -Wall -g
MAKECMDGOALS := $(filter-out clean, $(MAKECMDGOALS))
.PHONY: $(MAKECMDGOALS)
$(MAKECMDGOALS):
$(CC) $(CFLAGS) $#.c -o Main-$#
clean:
rm -f *.o
Here the lines
$(MAKECMDGOALS):
$(CC) $(CFLAGS) $#.c -o Main-$#
will generate separate build targets for each word in MAKECMDGOALS.
Note, we need this Makefile to know that 'clean' is a target for removing stuff, but not to attempt build Main-clean. This why we remove clean from MAKECMDGOALS using filter-out function.
So if we run make a b clean, the build system will generate automatically targets for building Main-a and Main-b and then use already written clean target
Disclaimer -- this is a non-standard use of Make, and will therefore open up all kinds of corner cases, so I don't recommend it. This is better suited for a shell script calling make. That being said... it is an interesting question.
You can't do make xxx clean, and not have it try to build xxx (unless you do some really nasty cludge using recursive make, but I won't go there). You could do something like make clean-xxx though, as follows:
%:Main-%
Main-%:%.cpp
$(CC) $(CFLAGS) $< -o Main-$#
clean-%:
rm Main-$*
Notice that %-clean has a shorter stem, and therefor takes precedence over the % if the make target starts with clean-.

Easy way to build objects for target and x86 at the same time

Currently, this is how I build my object files for my x86 compiler.
CC=g++
%.o: %.cpp
$(CC) $(CFLAGS) $(INCPATH) $(LIBPATH) -DPC -c $^ -o $#
How can I easily switch between g++ and my cross compiler? How can I compile both x86 and binaries for my target at the same time? I seem to be limited to compiling with only one compiler right now. Is there a way to come about this without having to list all my object files one by one?
You could pass the tool chain while giving make
Just an extra variable CROSS_COMPILE would do that
The makefile would rather look like this
CROSS_COMPILE :=
CC=$(CROSS_COMPILE)g++
%.o: %.cpp
$(CC) $(CFLAGS)$(INCPATH) $(LIBPATH) -DPC -c $^ -o $#
So if u just give make then CC is used as g++ and get compiled for x86, if you give make CROSS_COMPILE=arm-none-linux-gnueabi- then it would be compiled for ARM
You can use whatever the tool chain you want the concept remains the same
Sagar's answer does address how to switch between compilers, but does not address how to both do that and the main part of the question, which is how to do both targets at the same time.
To do both targets at the same time, you probably want to separate the objects into directories related to the compiler or target used, and then based on the directory of object, figure out what compiler to use.
So, something like below, in the simplest case, where the sources are in current directory, and the directory is the same as the compiler name. Fill in the user-defined COMPILER function with how you like to calculate your compiler name, based on the directory of the object file, which is the argument $1 to the function.
define COMPILER
$1
endef
.PRECIOUS: %/.
%/.:
mkdir -p $#
.SECONDEXPANSION:
%.o: $$(notdir $$*.cpp) | $$(#D)/.
$(call COMPILER, $(#D)) -c $< -o $#

Makefile - Dependency generation

I am trying to create a makefile that automatically compiles and links my .cpp files into an executable via .o files. What I can't get working is automated (or even manual) dependency generation. When i uncomment the below commented code, nothing is recompiled when i run make build. All i get is make: Nothing to be done for 'build'., even if x.h (or any .h file) has changed. I've been trying to learn from this question: Makefile, header dependencies, dmckee's answer, especially. Why isn't this makefile working?
Clarification: I can compile everything, but when I modify any header file, the .cpp files that depend on it aren't updated. So, if I for instance compile my entire source, then I change a #define in the header file, and then run make build, and I get Nothing to be done for 'build'. (when I have uncommented either commented chunks of the below code).
CC=gcc
CFLAGS=-O2 -Wall
LDFLAGS=-lSDL -lstdc++
SOURCES=$(wildcard *.cpp)
OBJECTS=$(patsubst %.cpp, obj/%.o,$(SOURCES))
TARGET=bin/test.bin
# Nothing happens when i uncomment the following. (automated attempt)
#depend: .depend
#
#.depend: $(SOURCES)
# rm -f ./.depend
# $(CC) $(CFLAGS) -MM $^ >> ./.depend;
#
#include .depend
# And nothing happens when i uncomment the following. x.cpp and x.h are files in my project. (manual attempt)
#x.o: x.cpp x.h
clean:
rm -f $(TARGET)
rm -f $(OBJECTS)
run: build
./$(TARGET)
build: $(TARGET)
$(TARGET): $(OBJECTS)
#mkdir -p $(#D)
$(CC) $(LDFLAGS) $(OBJECTS) -o $#
obj/%.o: %.cpp
#mkdir -p $(#D)
$(CC) -c $(CFLAGS) $< -o $#
This may take a few iterations.
1) I can't reproduce your results from your first approach (and you must be clearer than "nothing happens"-- does Make actually produce no output?). This:
depend: .depend
.depend: $(SOURCES)
rm -f ./.depend
$(CC) $(CFLAGS) -MM $^ >> ./.depend;
include .depend
seems to work as intended. I suggest you try $(info sources: $(SOURCES)) to verify that that variable contains the filenames you think it does.
2) I can't reproduce your results from your second approach (and you must be clearer than "nothing happens"-- does Make actually produce no output?). You tried x.o: x.cpp x.h when the first approach was commented out, is that right?
EDIT:
Let's concentrate on x.o. Does it contain #include "x.h"? When you uncomment the first section and make x.o, does Make produce (or modify) .depend? Is there a line in .depend that pertains to x.o, and if so what is it? If you then modify x.h and then make x.o, what does Make do?
You resolve only one kind of dependency with $(CC) -MM. There are various others like changed command options (e.g. -DDO_SOMETHING_ELSE), or a different set of symbols exported by a library. Traditional makes offer you lots of fun debugging inconsistent executables!
That's where makepp comes in. Dependencies are detected automatically. It not only rebuilds targets whenever any kind of dependency warrants this. It even chains everything together and builds what is needed from bottom up. I.e. if your linker has a -lmystuff option and you have a rule to build libmystuff.so or .a, that's all it takes, it will get built in time. Likewise you can include files that don't even exist yet — impossible with your solution.

How to make a SIMPLE C++ Makefile

We are required to use a Makefile to pull everything together for our project, but our professor never showed us how to.
I only have one file, a3driver.cpp. The driver imports a class from a location, "/user/cse232/Examples/example32.sequence.cpp".
That's it. Everything else is contained with the .cpp.
How would I go about making a simple Makefile that creates an executable called a3a.exe?
Since this is for Unix, the executables don't have any extensions.
One thing to note is that root-config is a utility which provides the right compilation and linking flags; and the right libraries for building applications against root. That's just a detail related to the original audience for this document.
Make Me Baby
or You Never Forget The First Time You Got Made
An introductory discussion of make, and how to write a simple makefile
What is Make? And Why Should I Care?
The tool called Make is a build dependency manager. That is, it takes care of knowing what commands need to be executed in what order to take your software project from a collection of source files, object files, libraries, headers, etc., etc.---some of which may have changed recently---and turning them into a correct up-to-date version of the program.
Actually, you can use Make for other things too, but I'm not going to talk about that.
A Trivial Makefile
Suppose that you have a directory containing: tool tool.cc tool.o support.cc support.hh, and support.o which depend on root and are supposed to be compiled into a program called tool, and suppose that you've been hacking on the source files (which means the existing tool is now out of date) and want to compile the program.
To do this yourself you could
Check if either support.cc or support.hh is newer than support.o, and if so run a command like
g++ -g -c -pthread -I/sw/include/root support.cc
Check if either support.hh or tool.cc are newer than tool.o, and if so run a command like
g++ -g -c -pthread -I/sw/include/root tool.cc
Check if tool.o is newer than tool, and if so run a command like
g++ -g tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
Phew! What a hassle! There is a lot to remember and several chances to make mistakes. (BTW-- the particulars of the command lines exhibited here depend on our software environment. These ones work on my computer.)
Of course, you could just run all three commands every time. That would work, but it doesn't scale well to a substantial piece of software (like DOGS which takes more than 15 minutes to compile from the ground up on my MacBook).
Instead you could write a file called makefile like this:
tool: tool.o support.o
g++ -g -o tool tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
-Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
tool.o: tool.cc support.hh
g++ -g -c -pthread -I/sw/include/root tool.cc
support.o: support.hh support.cc
g++ -g -c -pthread -I/sw/include/root support.cc
and just type make at the command line. Which will perform the three steps shown above automatically.
The unindented lines here have the form "target: dependencies" and tell Make that the associated commands (indented lines) should be run if any of the dependencies are newer than the target. That is, the dependency lines describe the logic of what needs to be rebuilt to accommodate changes in various files. If support.cc changes that means that support.o must be rebuilt, but tool.o can be left alone. When support.o changes tool must be rebuilt.
The commands associated with each dependency line are set off with a tab (see below) should modify the target (or at least touch it to update the modification time).
Variables, Built In Rules, and Other Goodies
At this point, our makefile is simply remembering the work that needs doing, but we still had to figure out and type each and every needed command in its entirety. It does not have to be that way: Make is a powerful language with variables, text manipulation functions, and a whole slew of built-in rules which can make this much easier for us.
Make Variables
The syntax for accessing a make variable is $(VAR).
The syntax for assigning to a Make variable is: VAR = A text value of some kind
(or VAR := A different text value but ignore this for the moment).
You can use variables in rules like this improved version of our makefile:
CPPFLAGS=-g -pthread -I/sw/include/root
LDFLAGS=-g
LDLIBS=-L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
-lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz \
-Wl,-framework,CoreServices -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root \
-lm -ldl
tool: tool.o support.o
g++ $(LDFLAGS) -o tool tool.o support.o $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is a little more readable, but still requires a lot of typing
Make Functions
GNU make supports a variety of functions for accessing information from the filesystem or other commands on the system. In this case we are interested in $(shell ...) which expands to the output of the argument(s), and $(subst opat,npat,text) which replaces all instances of opat with npat in text.
Taking advantage of this gives us:
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
tool: $(OBJS)
g++ $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
g++ $(CPPFLAGS) -c tool.cc
support.o: support.hh support.cc
g++ $(CPPFLAGS) -c support.cc
which is easier to type and much more readable.
Notice that
We are still stating explicitly the dependencies for each object file and the final executable
We've had to explicitly type the compilation rule for both source files
Implicit and Pattern Rules
We would generally expect that all C++ source files should be treated the same way, and Make provides three ways to state this:
suffix rules (considered obsolete in GNU make, but kept for backwards compatibility)
implicit rules
pattern rules
Implicit rules are built in, and a few will be discussed below. Pattern rules are specified in a form like
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
which means that object files are generated from C source files by running the command shown, where the "automatic" variable $< expands to the name of the first dependency.
Built-in Rules
Make has a whole host of built-in rules that mean that very often, a project can be compile by a very simple makefile, indeed.
The GNU make built in rule for C source files is the one exhibited above. Similarly we create object files from C++ source files with a rule like $(CXX) -c $(CPPFLAGS) $(CFLAGS).
Single object files are linked using $(LD) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS), but this won't work in our case, because we want to link multiple object files.
Variables Used By Built-in Rules
The built-in rules use a set of standard variables that allow you to specify local environment information (like where to find the ROOT include files) without re-writing all the rules. The ones most likely to be interesting to us are:
CC -- the C compiler to use
CXX -- the C++ compiler to use
LD -- the linker to use
CFLAGS -- compilation flag for C source files
CXXFLAGS -- compilation flags for C++ source files
CPPFLAGS -- flags for the c-preprocessor (typically include file paths and symbols defined on the command line), used by C and C++
LDFLAGS -- linker flags
LDLIBS -- libraries to link
A Basic Makefile
By taking advantage of the built-in rules we can simplify our makefile to:
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
tool.o: tool.cc support.hh
support.o: support.hh support.cc
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) tool
We have also added several standard targets that perform special actions (like cleaning up the source directory).
Note that when make is invoked without an argument, it uses the first target found in the file (in this case all), but you can also name the target to get which is what makes make clean remove the object files in this case.
We still have all the dependencies hard-coded.
Some Mysterious Improvements
CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)
SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))
all: tool
tool: $(OBJS)
$(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)
depend: .depend
.depend: $(SRCS)
$(RM) ./.depend
$(CXX) $(CPPFLAGS) -MM $^>>./.depend;
clean:
$(RM) $(OBJS)
distclean: clean
$(RM) *~ .depend
include .depend
Notice that
There are no longer any dependency lines for the source files!?!
There is some strange magic related to .depend and depend
If you do make then ls -A you see a file named .depend which contains things that look like make dependency lines
Other Reading
GNU make manual
Recursive Make Considered Harmful on a common way of writing makefiles that is less than optimal, and how to avoid it.
Know Bugs and Historical Notes
The input language for Make is whitespace sensitive. In particular, the action lines following dependencies must start with a tab. But a series of spaces can look the same (and indeed there are editors that will silently convert tabs to spaces or vice versa), which results in a Make file that looks right and still doesn't work. This was identified as a bug early on, but (the story goes) it was not fixed, because there were already 10 users.
(This was copied from a wiki post I wrote for physics graduate students.)
I've always thought this was easier to learn with a detailed example, so here's how I think of makefiles. For each section you have one line that's not indented and it shows the name of the section followed by dependencies. The dependencies can be either other sections (which will be run before the current section) or files (which if updated will cause the current section to be run again next time you run make).
Here's a quick example (keep in mind that I'm using 4 spaces where I should be using a tab, Stack Overflow won't let me use tabs):
a3driver: a3driver.o
g++ -o a3driver a3driver.o
a3driver.o: a3driver.cpp
g++ -c a3driver.cpp
When you type make, it will choose the first section (a3driver). a3driver depends on a3driver.o, so it will go to that section. a3driver.o depends on a3driver.cpp, so it will only run if a3driver.cpp has changed since it was last run. Assuming it has (or has never been run), it will compile a3driver.cpp to a .o file, then go back to a3driver and compile the final executable.
Since there's only one file, it could even be reduced to:
a3driver: a3driver.cpp
g++ -o a3driver a3driver.cpp
The reason I showed the first example is that it shows the power of makefiles. If you need to compile another file, you can just add another section. Here's an example with a secondFile.cpp (which loads in a header named secondFile.h):
a3driver: a3driver.o secondFile.o
g++ -o a3driver a3driver.o secondFile.o
a3driver.o: a3driver.cpp
g++ -c a3driver.cpp
secondFile.o: secondFile.cpp secondFile.h
g++ -c secondFile.cpp
This way if you change something in secondFile.cpp or secondFile.h and recompile, it will only recompile secondFile.cpp (not a3driver.cpp). Or alternately, if you change something in a3driver.cpp, it won't recompile secondFile.cpp.
Let me know if you have any questions about it.
It's also traditional to include a section named "all" and a section named "clean". "all" will usually build all of the executables, and "clean" will remove "build artifacts" like .o files and the executables:
all: a3driver ;
clean:
# -f so this will succeed even if the files don't exist
rm -f a3driver a3driver.o
EDIT: I didn't notice you're on Windows. I think the only difference is changing the -o a3driver to -o a3driver.exe.
Why does everyone like to list out source files? A simple find command can take care of that easily.
Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...
appname := myapp
CXX := clang++
CXXFLAGS := -std=c++11
srcfiles := $(shell find . -name "*.C")
objects := $(patsubst %.C, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
You had two options.
Option 1: simplest makefile = NO MAKEFILE.
Rename "a3driver.cpp" to "a3a.cpp", and then on the command line write:
nmake a3a.exe
And that's it. If you're using GNU Make, use "make" or "gmake" or whatever.
Option 2: a 2-line makefile.
a3a.exe: a3driver.obj
link /out:a3a.exe a3driver.obj
I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.
appname := myapp
CXX := g++
CXXFLAGS := -Wall -g
srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.
Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this (note that the indent must be a TAB):
main_target : source1 source2 etc
command to build main_target from sources
source1 : dependents for source1
command to build source1
There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them.
So your makefile will look something like this.
a3a.exe : a3driver.obj
link /out:a3a.exe a3driver.obj
a3driver.obj : a3driver.cpp
cc a3driver.cpp
I suggest (note that the indent is a TAB):
tool: tool.o file1.o file2.o
$(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $#
or
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o
The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).
Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).
Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.
Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:
CFLAGS = -Wall
LDLIBS = -lm
One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:
CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)
The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:
override CPPFLAGS += -MMD
include $(wildcard *.d)
-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.
For sure, a well written Makefile should also include clean and distclean rules:
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.
The all rule is also appreciated. In order to work, it should be the first rule of your file:
all: tool
You may also add an install rule:
PREFIX = /usr/local
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin
DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.
One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).
So to summarise, your full Makefile should look like:
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)
all: tool
tool: tool.o file1.o file2.o
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin