Dumb question re makefile variables

Max Okumoto okumoto at ucsd.edu
Thu Jan 6 13:48:20 PST 2005


walt wrote:
Okay, I understand that the typical '#define FOO 1' statement
in a C header file is read by the C pre-processor, and the
similar FOO=1 in a Makefile is read my 'make', and a shell
environment variable (setenv FOO 1) is read by the shell.
There seems to be some relationship between the three kinds of
variables -- but the connection is very confusing to me.
The differences between gnumake and bsdmake may also figure
into my confusion.
Can someone explain this to me like I was six years old?
(That was a line from some courtroom drama movie that was
otherwise completely forgetable.)
If there are specific parts of the man pages which spell
this out I've managed to misunderstand them -- but by all
means point me back to them.
Thanks for any clues!

The variables really are not related.  You can pass
information from the shell to make and the compiler.
The make program imports variables from its running environment.
So any exported variable in your shell are visible from withing
make.  Or you can explicitly pass values to make.
Most compilers require that you explicitly pass values via
the -D option.
Hmmmm... maybe we can start with some examples.

Lets say you have a program in file called foo.c

% cat foo.c
#include <stdio.h>
#define	BUGSTRING	"Max's code has bugs"

int
main(int argc, char *argv[])
{
	printf("What is wrong: %s\n", BUGSTRING);
	printf("What is true: %s\n", SOMESTRING);
	return 0;
}
If you compiled the program with gcc and ran it you would get
the following.
% gcc -DSOMESTRING=\"xyz\" foo.c -o prog0
% ./prog0
What is wrong: Max's code has bugs
What is true: xyz
If you set a shell enviornment variable, compile using gcc, and ran the 
program you would get the following.
% setenv ALPHA '"AOL_MSN"'
% gcc -DSOMESTRING=$ALPHA foo.c -o prog1
% ./prog1
What is wrong: Max's code has bugs
What is true: AOL_MSN

If you had the following makefile:

% cat Makefile
BARBAR = \"def\"
TARGETS = prog2 prog3 prog4

all: ${TARGETS}

prog2: foo.c
        gcc -DSOMESTRING=\"abc\" foo.c -o $@
prog3: foo.c
        gcc -DSOMESTRING=${BARBAR} foo.c -o $@
prog4: foo.c
        gcc -DSOMESTRING=${GAMA} foo.c -o $@
clean:
        rm -f ${TARGETS}
And you ran it with a shell variable GAMA set you would get the following:

% setenv GAMA '\"Max_was\"'
% make
gcc -DSOMESTRING=\"abc\" foo.c -o prog2
gcc -DSOMESTRING=\"def\" foo.c -o prog3
gcc -DSOMESTRING=\"Max_was\" foo.c -o prog4
% ./prog2
What is wrong: Max's code has bugs
What is true: abc
% ./prog3
What is wrong: Max's code has bugs
What is true: def
% ./prog4
What is wrong: Max's code has bugs
What is true: Max_was
				Max Okumoto





More information about the Users mailing list