Dumbo
Dumbo

Reputation: 14122

make command to replace constants in code

Sorry if this is a primitive question but I am really new in linux. Is there a way to replace constants in source code while building the application using make command?

I know the next possible method is to change the header files used in the source code, but I ask this because I have to program multiple microcontrollers and each one should have a unique integer as its number (this number is assigned as a constant in the code).

Any tips will be appreciated!

Upvotes: 1

Views: 252

Answers (2)

Jens
Jens

Reputation: 72717

You could use a C language macro passed on the command line to the compiler. The usual Makefile snippet would look something like

CFLAGS = -DVERSION_INT=42 -DVERSION_STRING=\"Frobozz Magic Frobnicator (TM)\"

main: main.c
         $(CC) $(CFLAGS) -o $@ main.c

In main.c you might have

static int version = VERSION_INT;
static char vers[] = VERSION_STRING;

Upvotes: 3

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136485

It is often done by defining preprocessor macros when invoking the compiler, e.g.:

# Makefile
NUMBER := 42
%.o : %.c
    gcc -c -o $@ ${CPPFLAGS} ${CFLAGS} -DNUMBER=${NUMBER} $<

In a source file:

// some.c
int number = NUMBER;

Upvotes: 2

Related Questions