Home > Back-end >  C Makefile: How to build environment variable into executable
C Makefile: How to build environment variable into executable

Time:07-01

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?

CodePudding user response:

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;
}

CodePudding user response:

Makefile:

CC=gcc
CFLAGS=-I
BUILD_TIME := '"$(shell date)"'

example: example.c
    $(CC) -o example example.c -DBUILD_TIME=$(BUILD_TIME)

example.c:

#include <stdio.h>

void main()
{
    printf("BUILD_TIME: %s\n", BUILD_TIME);
}
$ make
gcc -o example example.c -DBUILD_TIME='"Thu 30 Jun 2022 10:46:26 AM EDT"'
$ ./example 
Executable was built on: Thu 30 Jun 2022 10:46:26 AM EDT

Cheers!

  • Related