Reputation: 63
I am trying to create a Makefile but am really struggling. I have 3 files; main.cpp, garage.cpp, and garage.hpp. The following command works but I cannot figure out how to turn it into a makefile. Any help would be greatly appreciated. The -std=c++0x is important because if I remove that and replace it with something else it won't compile. Thanks again.
Working
g++ -std=c++0x -Wall -o main main.cpp garage.hpp garage.cpp
Upvotes: 6
Views: 23629
Reputation: 100836
FYI, it's not right to add header files (garage.hpp
) to the compile/link line. Only source files (.cpp
) should be put on the compile line.
@gowrath's solution is easy to understand but it's exactly the same as your command line solution: it doesn't take advantage of any of make's capabilities. It would be easier to just write a shell script or alias to do this than use a makefile.
@Rahul's solution spells everything out, but doesn't take advantage of any features of make that allow you to reduce typing or effort when writing a makefile.
Make actually has a large number of built-in rules. In order to customize them you simply set the values of standard variables and make will do the rest. You could write this makefile:
CXX = g++
CXXFLAGS = -std=c++0x -Wall
OBJECTS = main.o garage.o
main: $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $@ $^
$(OBJECTS): garage.hpp
The link rule uses automatic variables to avoid having to retype the target (main
) or prerequisites (main.o
, garage.o
).
The last line ensures that if the garage.hpp
file changes, make knows it has to recompile the source files. You don't have to write rules to tell make how to compile the source files: it already knows how to do it.
Upvotes: 10
Reputation: 272
Makefile is very effective way of compiling our code. Makefile uses time stamp to detect any changes in file and compile only those file that are changed. This saves lot of time.
Below makefile will do your job perfectly.
output: main.o garage.o
g++ -std=c++0x -Wall main.o garage.o -o output
main.o: main.cpp
g++ -c main.cpp
garage.o: garage.cpp garage.hpp
g++ -c garage.cpp
clean:
rm *.o output
Spaces before g++
and rm
command is a tab
Name this file as Makefile
to compile type make
. This will create a executable named output
And to run the executable using ./output
Upvotes: 2
Reputation: 3224
The most straightforward way to do this is to just have this in your Makefile (make sure the space before the second line is a single tab):
all:
g++ -std=c++0x -Wall -o main main.cpp garage.hpp garage.cpp
This is certainly not the best way but if you just want to compile it, this is your solution. Read a tutorial on make files to get a more detailed understanding.
Upvotes: 1