Q123
Q123

Reputation: 319

compile c++ code using makefile dynamically

It is about makefile and I wonder if makefile can compile cpp files dynamically.

Suppose I have main.cpp, a.cpp, b.cpp, and c.cpp files.(probably d.cpp, e.cpp and more can be added)

main.cpp file has main() function and a, b and c have their own functions.

Sometimes I only want to compile main.cpp, a.cpp and b.cpp files and link them.

But sometimes compile main.cpp, b.cpp and c.cpp files and link. No rules for what files I want to choose to compile.

What I think is like

make a b

make b c

make a c

or

make a b c

then only the file name specified can be compiled and link with main.cpp file.

Is there a good way for this to be done?

Thank you.

Upvotes: 0

Views: 355

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 28920

There is a simple solution: make variables that you can pass on the command line. They take precedence over the definitions in the Makefile.

$ cat Makefile
SRCS = $(filter-out main,$(patsubst %.cpp,%,$(wildcard *.cpp)))

main: main.o $(patsubst %,%.o,$(SRCS))
    $(CXX) -o $@ $^

clean:
    rm -f $(wildcard *.o) main

Then, if you want to link only a and b:

$ make SRCS="a b"
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++ -o main main.o a.o b.o

If you want to link only c and d:

$ make clean
rm -f a.o b.o main.o main
$ make SRCS="c d"
c++    -c -o main.o main.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o c.o d.o

And the default:

$ make clean
rm -f c.o d.o main.o main
$ make
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o a.o b.o c.o d.o

If the default does not make sense (e.g. because methods are defined in several source files), change the default value of SRCS in the Makefile:

SRCS = a b

Note: do not mix up make variables, which definition appears after the make command on the command line: make ... VAR=VALUE ... and the environment variables that you can pass to the make process: VAR=VALUE make .... There are relations between the two but they are completely different things.

Upvotes: 1

Related Questions