Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a C macro in a makefile?

Tags:

Is it possible to put the equivalent of #define VAR (in a C program) into a makefile, so that one can control which part of the program should be compiled?

like image 452
Richard Avatar asked Mar 14 '11 17:03

Richard


People also ask

How do I add a macro in makefile?

To use a macro in a makefile, type $(MacroName) , where MacroName is a defined macro. You can use either braces or parentheses to enclose MacroName . MAKE expands macros at various times depending on where they appear in the makefile: Nested macros are expanded when the outer macro is invoked.

How do you define a macro in C?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. Here, when we use c in our program, it is replaced with 299792458 .

What is $@ in makefile?

$@ is the name of the target being generated, and $< the first prerequisite (usually a source file). You can find a list of all these special variables in the GNU Make manual.


2 Answers

Accordingly to cc manpage on linux

-D name=definition            The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive.  In            particular, the definition will be truncated by embedded newline characters. 
like image 60
Zimbabao Avatar answered Oct 07 '22 17:10

Zimbabao


Edit your Makefile to show

CFLAGS=-D VAR1 -D VAR2=*something*

If you are using default rules in the Makefile, this should work automatically. If you do not, and are invoking the C compiler explicitely, just make sure you are writing something along the lines of

$(CC) $(CFLAGS) -c -o $@ $<

Even more cute if the fact the CFLAGS=...above can be used on the command line rather than written in the Makefile (read man(1) manual page); this allows for easy reconfiguration of your compilation parameters at last moment, but the parameters won't be kept.

Best practices include using CPPFLAGS instead of CFLAGS, and using += instead of =; however support for these features are not as universal as the above, and depend on your make system.

like image 28
AntoineL Avatar answered Oct 07 '22 15:10

AntoineL