Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C Makefile: How to build environment variable into executable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading