How Makefiles Work
The way I see it, a
Makefilelets you build your code easily without anIDE. But modernIDEs do so much work for us that we no longer understand how a program is compiled, linked and executed. For us, it’s quite necessary to understand how theIDEitself works.
VS? NO !!!
How exactly does
VScompile, link and execute our code?
For the detailed process see How a compiler works
1 | cl /EHsc /Femy.exe test.cpp |
1 |
|
gcc aspires to be the standard compiler, so it makes sense for it to be open source. vim/emacs aspire to be the standard editors for programmers, so it makes sense for them to be open source too. apache aspires to be the standard web server platform, so it makes sense for it to be open source. android aspires to be the standard mobile internet platform, so it makes sense for it to be open source.
Makefile Basics
1 | target... : requisites... |
The
tabbefore the command is required. For a Makefile, lines starting with atabare commands.
What’s Clever About Makefiles
The first big advantage of
Makefile:
After you change one file, it does not recompile the whole project.
It only compiles the changed files (isn’t that what IDEs do?)
If you see garbled output, use
chcp 65001to switch toutf-8encoding
The second big advantage: People reading the source code can clearly see from the
Makefilehow the program is built and how a given file is produced. If you only look at all those.hand.cppfiles in anIDE, even a genius would need a long time to read through them.
In a Makefile, long content can be wrapped with
\. The rules only tellmaketwo things: the file dependencies and how to generate the target file.
- Generally, make executes commands with the standard UNIX shell, i.e.
/bin/sh.
The third big advantage: The universal source-package installation greatly promoted the spread of open source software. Almost every piece of software around us carries traces of open source software, and the explosion of open source is inseparable from the popularity of
makefile— it made programmers’ work so much simpler.
Using C++ Libraries
Please download the example program
$^: represents all the dependency files
$@: represents the target
$<: represents the first dependency file
A Slightly More Complex Example
Finally, let me introduce the three-line love poem of Linux:
1 | ./configure |
1 | wget http://ftp.gnu.org/gnu/tar/tar-latest.tar.xz # download the tar source package |
Some Simple Reference Documents
If you’re interested in LFS and already have some Linux basics, you can download the docs and give it a try.
LFS downloads