Makefile variables and getenv()
Makefile
There are three types of variables in the Makefile
- makes’ environment variables
- command-line
- variables defined in the Makefile
Priority
- command-line
- variables defined in the Makefile
- environment variable
There are an exception (-e
flag):
Variables in
make
can come from the environment in whichmake
is run. Every environment variable thatmake
sees when it starts up is transformed into amake
variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile. See Summary of Options. But this is not recommended practice.)
getenv()
When
make
runs a recipe, some variables defined in the makefile are placed into the environment of each commandmake
invokes. By default, only variables that came from themake
’s environment or set on its command line are placed into the environment of the commands. You can use theexport
directive to pass other variables. See Communicating Variables to a Sub-make
, for full details.
So according to the text above, we can use getenv in C file to get the variable passed by the command line. Here is an example:
C file:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *mainargs = NULL;
mainargs = getenv("mainargs");
if(mainargs)
printf("mainargs = %s!!!\n", mainargs);
mainargs = getenv("hello");
if(mainargs)
printf("hello = %s!!!\n", mainargs);
return 0;
}
Makefile:
hello=123
run: getenv
@./getenv
@echo $(hello)
getenv : getenv.c
@gcc -o getenv getenv.c
we can see that the command-line variable can be gotten through getenv
, but the hello
variable defined in the Makefile cannot be gotten through getenv
.