I’m trying to get an environment variable passed from the shell into an executable when it gets compiled, and be able to access that variable. For example, say I wanted to build the time something was compiled into the application when it gets built so I can see when the executable was built. How do I structure the Makefile and C program to do that?
Example C program:
#include <stdio.h>
#define variable 2
void main(){
printf("Variable: %d\n", variable);
}
Example Makefile:
CC=gcc
CFLAGS=-I
BUILD_TIME=$(date)
example: example.c
$(CC) -o example example.c
How can these two files be modified to make the BUILD_TIME variable available to the C file?
>Solution :
You can use the -D
option to create preprocessor variables on the command line.
CC=gcc
CFLAGS=-I
BUILD_TIME=`date`
example: example.c
$(CC) -D "BUILD_TIME=\"$(BUILD_TIME)\"" -o example example.c
#include <stdio.h>
int main()
{
printf("build time = %s\n", BUILD_TIME);
return 0;
}