Let's make a Makefile

by Forrest Sheng Bao http://fsbao.net

Make is a great tool on Linux and Mac. I have never used it on Windows, coz I seldom use Windows, maybe once per two weeks. Windows sucks, flat suck, especially Windows Vista.

So, what is make? Generally, make is a program to control the compiling process, what you wanna compile, what you don't wanna compile, what you wanna compile to and what you wanna compile from. So, in order to let make know these, we should write a Makefile. Makefile generally can be used for two cases: 1) you have many files 2) your file has many preprocessors/switches. For example, let's take a look at the hello.cpp
#include 

#ifdef ONE
int main ()
{
std::cout << "Hello world in ANSI-C++\n";
return 0;
}
#endif

#ifdef TWO
int main ()
{
std::cout << "preprocessor works\n";
return 0;
}
#endif
If you add -D ONE as the option to g++ compiler, then only the first part will be compiled. Otherwise, only the second part will be compiled. You can type following two lines to generate different executable files:
g++ hello.cpp -D ONE -o one.out
g++ hello.cpp -D TWO -o two.out
Maybe sometimes you want the one.out and sometimes you want the two.out. So make can do this for you. You just need to save following lines as a file called Makefile
one:
g++ hello.cpp -D ONE -o one.out
two:
g++ hello.cpp -D TWO -o two.out
Then, when you type
make one
or omit the "one" you will get one.out. If you type
make two
, you will get two.out. So, actually, the syntax of Makefile is very easy
make parameter:
compiling command
And you just need to append make parameter after the make when you compile it from a Unix shell, such as
make one
. But actually, this is a simple case, you can add dependencies after the make parameter: line.

No comments: