I want to build an app and I have multiple modules stored in multiple directories. I’ve decided to follow this idea, i.e. to have a makefile in each directory and then to merge it. But – as a beginner programmer – I still do not see how to do that. First of all, how would such “partial” makefiles look like. They cannot have main function as there can be only one per binary, though when I try to compile it gcc complains for the undefined reference to main. Secondly, I have no idea how would putting all those modules together look like.
I would appreciate any help, but please try to keep your answers simple. Makefiles are still a bit of black magic to me.
Before you can do anything with a makefile, you must know how to do it without a makefile.
Since you are using gcc, I will assume that your source code is C++.
You haven’t told us what your directory structure looks like, so I’ll suppose that you have three source files in two directories:
primary/main.cc,other/foo.ccandother/bar.cc. (We can deal with header files likefoo.hlater.) And you want to buildmyApp.STEP 1: Doing It By Hand
To do this in one command, you might use:
This will compile the three source files and link the binary objects together into the executable
myApp.STEP 2: Doing It In Pieces (Do not attempt this until you can get the previous step to work perfectly.)
Instead of building with one command, you could take an intermediate step, compiling the source files into binary object files:
This will produce
alpha/main.o,beta/foo.oandbeta/bar.o. The compiler won’t complain aboutfooandbarlacking amain()function, because an object file doesn’t need one. Then link the objects together into an executable:STEP 3: Doing It Locally (Do not attempt this until you can get the previous step to work perfectly.)
Just like the previous step, but we act in
primary/andother/:STEP 4: Using a Makefile (Do not attempt this until you can get the previous step to work perfectly.)
We could have a makefile perform STEP 1, but that isn’t really necessary. Write a makefile in
primary(i.e.primary/makefile) like this:(That whitespace in fromt of
gcc...is a TAB.)Now try this:
STEP 5: Using Several Makefiles (Do not attempt this until you can get the previous step to work perfectly.)
Write a
other/makefile:and a makefile in the top directory, where you’re building
myApp:Now try this:
STEP 6: Using One Makefile That Calls Others (Do not attempt this until you can get the previous step to work perfectly.)
Edit the top makefile:
Now try:
If all of this works, what you have is a crude but effective makefile system. There are many refinements possible, when you’re ready to take the training wheels off.
EDIT:
If there are many source files in a subdirectory (e.g.
other/) and you don’t want to maintain a list in the top makefile by hand, there are several ways to handle it. This is one:But you should get these makefiles working and understand them, before you try any more streamlining.