Is it possible to set environment variable through a makefile? Is it possible to set environment variable through a makefile? unix unix

Is it possible to set environment variable through a makefile?


In Bash, you can specify environment variables in front of the command, e.g.,

MALLOC_PERTURB_=105 gcc test.c -o test

or

MALLOC_PERTURB_=105 ./test

(I believe only the run has to have this variable set, not the compile.)

Since you are on Linux there is a good chance Make will use Bash as shell and you can put the line above in your makefile.


Browning, setting an environment variable in the makefile is easy, and you have done so, but that is not what you want. That makes it take that value during the compile. But you want it to change malloc's behavior when you run the program.

Reading the man page you referenced confirms that you need to set the environment variable in the environment where your program is running. Also reading the comments, it is already mentioned that the makefiles that set the environment variable only do so for a test program, which they actually run as part of the build.

You do not want it in the makefile. You want it set while you actually run the program, which is what the other comments and answers are telling you how to do. Sorry for taking up an answer, but I needed more room to clear that up, plus it is the answer, for you. You already know how to do it. You just didn't know what it was, exactly.


You can set the "MALLOC_PERTURB_" value at compile time as well by passing the M_PERTURB option to the mallopt() function (glibc 2.4 or later). See http://man7.org/linux/man-pages/man3/mallopt.3.html for details.

So if you want your program to incorporate the setting of the environment variable "MALLOC_PERTURB_" at compile time, then something like this should work:

#include<stdlib.h>#include<stdio.h>#include <malloc.h> // for mallopt() and M_PERTURB#define N 50int main(){    char *chars;    int i;#if MALLOC_PERTURB_    mallopt( M_PERTURB, MALLOC_PERTURB_);#endif    if (NULL == (chars = malloc(N * sizeof(*chars))))        return EXIT_FAILURE;    free(chars);    for (i = 0; i < N; ++i)        printf("%c", chars[i]);    printf("\n");    return EXIT_SUCCESS;}

Then have your makefile pass the MALLOC_PERTURB_ value as a macro definition on the compiler command line (or whatever mechanism you want to use):

gcc -DMALLOC_PERTURB_=97 test.c -o test