0

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.

2
  • 3
    this sounds like an xy problem. source files can't be arbitrarily combined into a working executable...so there's some structure to the combinations you will put together, and that structure will dictate what makes for a 'good' solution. [if I may hazard a guess] You might find it more productive to state what you're trying to achieve, that this is a part of. Commented Dec 9, 2017 at 2:44
  • I agree with @lockcmpxchg8b. Explaining why you want to dynamically link different sets of files is probably going to get you a better answer. Commented Dec 9, 2017 at 2:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.