Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a simple makefile generic

Tags:

c++

makefile

I have a simple makefile to help me compile some examples:

   ex104: ex104.cpp
        $(CPP) ex104.cpp $(INCS) $(LINKFLAGS) $(COMPILEFLAGS) -o ex104  

   clean:   
        rm -f *.o $(EXECUTABLE)

Now, that works fine. The problem is: I would need to explicitly write a rule for each of the examples, thus copying the following line many, many times:

   ex104: ex104.cpp
        $(CPP) ex104.cpp $(INCS) $(LINKFLAGS) $(COMPILEFLAGS) -o ex104

Is there a way to generic-ize it a bit? So that I would end up with a command line like below that would build ex252 from ex252.cpp built automatically:

make ex252

Fortunately, it's a template-only library, so I always have to build from just one cpp file, and I do not need to keep track of object files.

like image 493
Michael Avatar asked Mar 12 '26 07:03

Michael


1 Answers

Make has a bunch of default rules and what you want should works if instead of your variables you are using the default one for flags to be given.

If your version of make does not have such default, this should add one (it correspond to GNU make default rule with some intermediary variables inlined and obsolete one removed) :

.cpp:
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $^ $(LDLIBS) -o $@

CXX is the C++ compiler

CXXFLAGS is the flags for the C++ compiler

CPPFLAGS is the flags for the preprocessor (they are common between C and C++ in gnu make)

LDFLAGS are the flags for linking

TARGET_ARCH allows to specify a target architecture

LDLIBS is the libraries to link

like image 130
AProgrammer Avatar answered Mar 13 '26 21:03

AProgrammer