beginner GNU Makefile Error - c++

This is my first, attempt at a, Makefile after necessity from a previous post.
Anyway here's the code
SortLab.exe : SelectionSort.o Main.o
g++ -o $# $^
SelectionSort.o : SelectionSort.cpp SelectionSort.h
Main.o : Main.cpp
#-------------------------------------------------------------
run: SortLab.exe
./SortLab.exe
clean:
rm -f *.o
rm -f *.exe
build: clean SortLab.exe
%.o: %.cpp
g++ -c $<
I intend to have SelectionSort.cpp & SelectionSort.h form an object file, and Main.cpp to form its own object file. Then finally create an executable. Main.cpp depends on SelectionSort.cpp, where do I go wrong?
Also where can I find what the different GNU commands mean, -o -c and such

You shouldn't need to define the %.o: %.cpp rule yourself, Make knows how to compile C++.
Indent with tabs, not spaces; Make is sensitive to the difference.
Every object file should depend on the headers included in the source files it depends on. You probably need Main.o : Main.cpp SelectionSort.h.
build shouldn't depend on clean, it defeats one of Make's main features (selectively recompilation when files have changed).
If you make build the first target, you can run Make without a target to get a full compile. It's customary to call the main target all.

Related

Makefile with multiple separate *.cpp files to output separate *.exe files in different dir

I am stuck, writing my Makefile.
Directory structure:
.\
Makefile
.\src\*.cpp(s)
.\bin
Desire: What I want to achieve with one Makefile.
Run: make
Output (Terminal):
g++ -g -Wall -c -o src/program1.o src/program1.cpp
g++ -g -Wall -c -o src/program2.o src/program2.cpp
g++ -g -Wall -c -o src/program3.o src/program3.cpp
g++ -g -Wall -c -o src/program4.o src/program4.cpp
Output (in /bin/)
program1.exe
program2.exe
program3.exe
program4.exe
EDIT:
CXX = g++
CXXFLAGS = -Wall -g3 -O0
SRC := ${wildcard src/*.cpp}
OBJS := $(SRC:.cpp=.o)
BIN := $(SRC:src/%.cpp=bin/%)
.PHONY: all
all: $(BIN)
$(BIN): $(OBJS)
$(CXX) -c $(CXXFLAGS) -o $(OBJS)
bin/%: src/%.o
$(CXX) -o $# $^
Error:
g++: warning: linker input file unused because linking not done
The introductory parts of the GNU make manual describe that all: $(BIN) creates a target all that depends on a target bin. That means make will try to create bin. Then you have $(BIN): $(OBJS) which says bin depends on all the object files, so make will try to create all the object files. Then there's a recipe for that rule that says, after you've created the object files run this command, which links together all the object files into a single program (bin).
So make is doing exactly what you asked it to do.
The problem is that is apparently not what you want it to do.
In your question you write, then take the original filenames of each *.cpp and add that to the executable which I don't fully understand, but I assumed that you want to link all the objects into a single executable, which is what your makefile does.
But then later you write: How can I output to bin directory and generate the correct executables?, but you never define what "correct executables" means, and this makes it sound like you want to turn each individual object file into its own executable; that's clearly not what your makefile does.
So before you can tell make what you want, first you have understand clearly what you want so you can write it in your makefile. And if you need us to help you write it into your makefile, you need to explain it clearly in your question so we can understand it.
Cheers!
ETA
OK so you want every source file to compile into an object file, then every object file to compile to a separate binary.
First compute the names of all the binaries you want to build:
SRCS := $(wildcard src/*.cpp)
BINS := $(SRCS:src/%.cpp=bin/%)
Now make a rule that depends on all the binaries:
all: $(BINS)
Now make a pattern rule that tells make how to build each one of those binaries:
bin/% : src/%.o
$(CXX) $(CXXFLAGS) -o $# $^ $(LDLIBS)
Now you're actually done, because make already has a built-in rule that knows how to build a .o file into the same directory where the .c file lives, so it can figure out how to build the src/x.o files on its own.
Try something like:
SRC:=${wildcard src/*.cpp}
OBJ:=$(patsubst %.cpp,%.o,${patsubst src/%,bin/%,${SRC}}}
to get the list of the object files, and the rule:
obj/%.o : src/%.cpp
${CXX} -o $# -c $<
for compiling into the right location.
EDIT You have now clarified that each file is a separate main.
SRC:=${wildcard src/*.cpp}
BIN:=$(patsubst %.cpp,,${patsubst src/%,bin/%,${SRC}}}
to get the list of the object files, and the rule:
bin/% : src/%.cpp
${CXX} -o $# $<
will write each output as an executable in bin. To kick it off:
all : ${BIN}

makefile: how to specify header files

I'm trying to write a makefile for all of my cpp prjects. After searching from the internet, I make a makefile as below:
g++11=g++ -std=c++11 -stdlib=libc++
CPPFILES=$(wildcard *.cpp)
OBJFILES=$(CPPFILES:.cpp=.o)
res.out: $(OBJFILES)
$(g++11) -lncurses -o $# $^ -g
#obj/%.o: %.cpp
%.o: %.cpp
$(g++11) -c -o $# $< -g
clean:
rm *.o *.out
I tried to use this file to compile my cpp projects and it worked well.
However, when I make some change in the header files, it doesn't work anymore because this makefile can't detect the modification in header files.
Is there any easy way to specify header files in the makefile?
Ofc I don't want to specify them one by one.
First of all, you should understand the concept of make.
Make is not only for compiling C++, it's a universal tool where a product (file) is built from other files. When you issue the make, it checks whether the top product should be rebuilt, based on the file change dates of dependencies. If rebuild is needed, first checks all the dependencies whether they should be rebuild... and so on. These bricks are called rules.
This is a rule:
target: dependency1 dependency2 ...
command1 to produce targets
command2
In case of a CPP project:
myapp: myapp.cpp myapp.hpp
g++ myapp.cpp -o myapp
More info: http://www.cs.cmu.edu/~gkesden/412-18/fall01/projects/proj1/make/makeintro.html

Makefile to build shared library

I've been building a C++11 library, and the number of header/source files has grown to the point where compiling programs invoking it, entails passing 20+ .cpp files to g++. I've been reading up on shared libraries and it seems to be the best solution.
However, as headers/source change frequently, I'm hoping to create a makefile that would automatically generate all the .so files from the headers and source.
To better demonstrate what I'm trying to do, I'll take one of my sub-libraries, Chrono and show how I would do this manually.
I first create the object files like so,
$ g++ -std=c++11 -fPIC -g -c -Wall ../src/Chrono/cpp/DateTime.cpp
$ g++ -std=c++11 -fPIC -g -c -Wall ../src/Chrono/cpp/Schedule.cpp
$ g++ -std=c++11 -fPIC -g -c -Wall ../src/Chrono/cpp/Duration.cpp
$ g++ -std=c++11 -fPIC -g -c -Wall ../src/Chrono/cpp/DayCount.cpp
So that I now have DateTime.o, Schedule.o, Duration.o, and DayCount.o in the current directory. I then create the .so file,
$ g++ -shared -Wl,-soname,libChrono.so.1 -o libChrono.so.1.0.1 DateTime.o Schedule.o Duration.o DayCount.o -lc
I then go,
$ rm ./*.o && ldconfig -n ./
So that my working directory now contains, libChrono.so.1.0.1 and the symlink libChrono.so.1.
There are quite a few subdirectories I need to do this for, so you can see that this quickly grows inefficient whenever changes to headers/source are made. I would be grateful if anyone can help me design a makefile that accomplishes all this simply by invoking make.
Thanks!
UPDATE:
Based on goldilock's advice and some digging, I managed to bang together:
CXX=g++
CFLAGS=-std=c++11
TARGET=./lib/libChrono.so.1.0.1
CHRONODIR=./src/Chrono
CHRONOSRC=$(wildcard $(CHRONODIR)/cpp/*.cpp)
CHRONOOBJ=$(join $(addsuffix ../obj/, $(dir $(CHRONOSRC))), $(notdir (CHRONOSRC:.cpp=.o)))
all: $(TARGET)
#true
clean:
#-rm -f $(TARGET) $(CHRONOOBJ)
./lib/libChrono.so.1.0.1: $(CHRONOOBJ)
#echo "======================="
#echo "Creating library file $#"
#echo "======================="
#$(CXX) -shared -Wl,-soname,$(join $(basename $#), .1) -o $# $^ -l
#echo "-- $# file created --"
$(CHRONODIR)/cpp/../obj/%.o : $(CHRONOSRC)
#mkdir -p $(dir $#)
#echo "============="
#echo "Compiling $<"
#$(CXX) $(CFLAGS) -fPIC -g -Wall -c $< -o $#
4 .o files are produced in lib/ but I get multiple definition complaints from ld. Before I was compiling the object files separately, but this unwinds CHRONOOBJ on one line. Any ideas?
Fortunately you included the origin of your problem:
I've been building a C++11 library, and the number of header/source files has grown to the point where compiling programs invoking it, entails passing 20+ .cpp files to g++.
Because this reveals a potential XY problem. The straightforward solution to this is to put object files into an archive (aka. a static library) and use that.
GNU make has an implicit rule for creating C++ .o files. It amounts to this:
%.o: %.cpp
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $<
Meaning, if you make DateTime.o in a directory with a makefile that doesn't redefine this, it will make DateTime.o. You may want to add things to $(CXXFLAGS) however, e.g.:
CXXFLAGS += -Wall -Wextra --std=c++11
If you intend to stick with the shared lib route, -fPIC can go there too. That one line could be your entire makefile.
However, you also want to put these together, so you must first declare all the objects and a rule for combining them:
OBJS = DateTime.o Schedule.o Duration.o
libChrono.a: $(OBJS)
ar crvs $# $^
This last line (see man ar) creates the archive (libChrono.a) containing all the objects in $(OBJS). You can then use this with whatever program by placing it in the same directory (or a directory in the library path) and linking -lChrono. Only the necessary parts will be extracted and compiled in. This saves you having to maintain a shared lib in a system directory.
If you still think you need a shared lib, $# and $^ are automatic variables; you can use similar methodology to create a .so, something along the lines of:
SO_FLAGS = -shared
libChrono.so.1.0.1: $(OBJS)
$(CXX) $(SO_FLAGS) -Wl,-soname,libChrono.so.1 -o $# $^ -lc
If that is your first rule, make will take care of everything: building first the objects and then the library. Notice this one has excluded your normal $(CXXFLAGS) to duplicate exactly the compiler line from the question.

"Optional" object file target in Makefile?

I have some code that is "optional": the rest of the program can be linked without it.
How do I properly create a Makefile that excludes it as a dependency if there is an error when creating the object file?
So far I have something like this:
OUT=my_program
OBJS=$(subst .cc,.o,$(wildcard *.cc))
all: $(OUT)
$(OUT): $(OBJS)
my_optional_file.o: other_target
.IGNORE: my_optional_file.o
The good: When processing the rule my_optional_file.o, this correctly ignores all errors.
The bad: When linking the output, my_optional_file.o is specified as an argument to the linker despite the fact that it was not built, making the linker fail because it was given a nonexistent file as input!
How do I exclude my_optional_file.o when there is an error in building it?
Use $(shell find . -maxdepth 1 -iname "*.o") with an explicit call to the linker.
Like :
$(OUT): $(OBJS)
$(CXX) $(LDFLAGS) $(shell find . -maxdepth 1 -iname "*.o") $(LDLIBS) -o $#
The reason is that when implicitly called, the linker command is called like this :
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $#
With $^ expanding to the content of $(OBJS). You need an explicit call to use specific files instead.
The $(wildcard *.o) function cannot be used because it is executed before the files are created so it is always empty.
Assuming your make is GNU make, here is one way of doing this.
Say my program prog has three source files main.c, necessary.c, optional.c
such that I want to link prog from all three .o files, if they get
built ( = a maximal build), but I will settle for main.o and necessary.o ( = a minimal build). (I waive the rationale for this).
A makefile to the purpose is:
.phony: all clean make_prog
max_objs=$(subst .c,.o,$(wildcard *.c))
all: make_prog
make_prog: $(max_objs)
$(MAKE) prog
prog: $(wildcard *.o)
gcc -o $# $^
clean:
rm -f prog *.o
.IGNORE: optional.o
To make prog I first make the phony target, make_prog, whose
prerequisites are all three .o files, but I ignore failure to make
optional.o. Then I make prog for real, and to do that I just
link whatever .o files I've got at this point. If optional.o
isn't there, it doesn't matter.
To be clear about the behaviour of this:-
If, initially, I have a maximal build of prog, then make a change that breaks
optional.c and re-make, no .o is re-made, so prog is not re-made. It
stays maximal.
If, initially, I have a minimal build of prog, then make a change that fixes
optional.c and re-make, optional.o is re-made, so prog is re-made. It
becomes maximal.
Failure to make optional.o excludes prog's dependency on it and introduces
no new ones. So if all other dependencies are satisfied, there's no need to
remake prog.
Now it might be the case that you actually want failure to make optional.o to
introduce a dependency on the failure to make optional.o, in the
sense that it would force prog to be rebuilt minimally.
A simple way to achieve that is by adding the line:
.INTERMEDIATE: optional.o
to the makefile, which will force optional.o always to be deleted at the end of a make.
This has the cost that optional.c will always be compiled, and consequently a maximal build will always be re-linked.
Lastly, someone might wonder why the makefile couldn't more simply be:
.phony: all clean
objs=$(subst .c,.o,$(wildcard *.c))
all: prog
prog: $(objs)
gcc -o $# $(wildcard *.o)
clean:
rm -f prog *.o
.IGNORE: optional.o
Well if we do a make from clean with that, the output is:
cc -c -o main.o main.c
cc -c -o necessary.o necessary.c
cc -c -o optional.o optional.c
gcc -o prog
gcc: fatal error: no input files
compilation terminated.
make: *** [prog] Error 4
That's because $(wildcard *.o) is expanded when the makefile is
parsed, and at that point no .o files exist. We need to be parsing
the makefile again when we expand this, having already made all
the .o files we can.
GNU make does not have optional dependencies. You can simulate that by not returning failure when it fails to build and filtering out non-existent objects when linking.

How to include a makefile into an other makefile?

I have some C++ classes, every one into his own folder with a makefile, test.cpp for testing purpose, etc.
Main folder
|-> Class1 folder
|-> Class2 folder
|-> Class2.1 folder
|-> Class2 folder
I have a main project, that must include these classes. I am trying to include all sub-makefiles into the main makefile.
I have tried with "INCLUDE POO/makefile", but this solution has 2 problems:
The path of the sub-makefiles is incorrect, so files are not found ("There is not rule to build the target 'Vector3D.cpp'").
The "test.cpp" file is overrided, probably because of the path problem.("warning: overriding recipe for target ...")
I would like all makefile independent, so I can copy/paste the class folder into a new project and it still working, or I may exec the makefile alone without changes on it.
So the question is: How to include (correctly) a makefile into another makefile?
Example, just for test purpose.
Main makefile (simplified)
include Vector3D/makefile
include Color/makefile
CPP = g++
CXXFLAGS = $(CXXINCS) -Wall -O0
all: main
main: main.o Vector3D.o Color.o
$(CPP) main.o Vector3D.o Color.o -o main
main.o: main.cpp
$(CPP) -c main.cpp -o main.o $(CXXFLAGS)
Sub-makefile example (simplified)
#Vector3D
CPP = g++
CXXFLAGS = $(CXXINCS) -Wall -O0
all: test
test: Vector3D.o test.o
$(CPP) Vector3D.o test.o -o test
Vector3D/test.o: test.cpp
$(CPP) -c test.cpp -o test.o $(CXXFLAGS)
Vector3D.o: Vector3D.cpp Vector3D.hpp
$(CPP) -c Vector3D.cpp -o Vector3D.o $(CXXFLAGS)
Similar for Color/makefile than Vector3D.
I would like all makefile independent, so I may copy/past the class folder into a new project and it still working, or I may exec the makefile alone without changes on it.
I'm pretty sure that's not possible. Your makefiles either need to be standalone, in which case you can make the top-level files invoke make in lower level directories recursively (so do not include them) or you can have a single non-recursive makefile formed by including other makefiles. I don't think it's possible to do both.
How to include (correctly) a makefile into an other makefile?
The only valid answer is "using the include directive" (other than the usual "it depends".) Any other advice depends on the structure of the makefiles. Makefiles designed to be included will obviously be easier to include. Just including some random makefile and hoping it will work ... won't work. Check out Implementing non-recursive make and Boilermake for how to make non-recursive makefiles work.
Note that there's no need to include them at the top of the file and doing so may be a bad idea, as the default target becomes the first one in the included file.
Thanks to #Jonathan-wakely to provide the initial concepts for this solution.
There are probably many things that may be improved, but it works.
Requirements summary:
Makefiles should work standalone
The main makefile will includes sub-makefiles
No conflicts or path problem should appear.
A simple solution is to call recursively makefiles:
Create a "normal" script for leaf makefiles
Using an empty target allow to execute always make calls for example "sub-make:" without any requirement after ":"
Use the "-C" parameter to set the root directory for the make call.
Create the final linking with binaries created by sub-makefiles.
Example for the main makefile:
#all make recursive calls
sub-make:
make -C Vector3D
make -C Color
#final linking
CPP = g++
FLAGS = $(CXXINCS) -Wall -O0
all: main
main: main.o Vector3D/Vector3D.o Color/Color.o
$(CPP) main.o Vector3D/Vector3D.o Color/Color.o -o main
main.o: main.cpp
$(CPP) -c main.cpp -o main.o $(FLAGS)
There is probably a better way to provide *.o binaries to the linker without writing all full path, but that is another problem.
Creating the clean target. For leaf makefiles, there are no special considerations to take, but for the main makefile, it must call sub-clean rules.
clean:
make -C Vector3D clean
make -C Color clean
rm -f *.o main
EDITING:
Here is the makefile structure I have done, for if it may be useful to anyone.
To work, All classes must be in it own folder with:
.hpp header
.cpp code
main.cpp for testing
Required classes (LIBS) directory are specified with "$(LIBSPATH)LibName" in relation to this makefile.
Makefile
#Following configuration may be set with a parameter:
# e.g: make FLAGS="-Wall -O0"
FLAGS = $(CXXINCS) -Wall -O0
#Configurable variables
EXEC = main
CLASS = World
LIBS = Color Vector3D Triangle
LIBSPATH = ../
#Static content
CPP = g++
OBJS = $(foreach dir, $(LIBS), $(LIBSPATH)$(dir)/$(dir))
all: $(EXEC)
clean:
rm -f *.o $(EXEC)
$(foreach dir,$(LIBS),make clean --no-print-directory -C $(LIBSPATH)$(dir);)
$(EXEC): $(CLASS).o $(EXEC).o $(OBJS:=.o)
$(CPP) $(CLASS).o $(OBJS:=.o) $(EXEC).o -o $(EXEC)
$(EXEC).o: $(EXEC).cpp
$(CPP) -c $(EXEC).cpp -o $(EXEC).o $(CXXFLAGS)
$(CLASS).o: $(CLASS).cpp $(CLASS).hpp
$(CPP) -c $(CLASS).cpp -o $(CLASS).o $(CXXFLAGS)
$(OBJS:=.o): $(OBJS:=.cpp) $(OBJS:=.hpp)
make --no-print-directory -C $(LIBSPATH)$(strip $(foreach dir,$(LIBS),$(if $(findstring $(dir),$#),$(dir))))