how does the C pre-processor interface with make?

Matthew Seaman m.seaman at infracaninophile.co.uk
Wed Dec 30 09:33:02 UTC 2009


Oliver Mahmoudi wrote:
> Hey folks,
> 
> I was wondering how the C pre-processor interfaces with make. Let's suppose
> that I have a little C program, something along the lines of:
> 
> #include <stdio.h>
> 
> int
> main()
> {
> #ifdef FOO
>      fprintf(stdout, "Hi, my name is foo.\n");
> #endif
> 
> #ifdef BAR
>      fprintf(stdout, "Hi, my name is bar.\n");
> #endif
> 
>      fprintf(stdout, "I am always here.\n");
> 
>      return(1-1);
> }
> 
> It is easy to control the pre-processor in the above code by defining the
> respective terms or leaving them out, however,
> I am trying to control the conditionals from out of a makefile.
> 
> This is essentially the way in which the kernel sources are compiled.
> 
> Any suggestions?

Yes.  You have to define your FOO and BAR variables on the cc(1) command
line using the -D flag, based on the equivalent settings in make.  Supposing
your little program is held in a file wibble.c, then in your Makefile you'ld
need something like this to compile and link it into a program called wibble:

.if defined(FOO)
CFLAGS+=   -DFOO
.endif

.if defined(BAR)
CFLAGS+=   -DBAR
.endif

wibble: wibble.c
	${CC} ${CFLAGS} ${LDFLAGS} ${.ALLSRC} -o ${.TARGET}


Then you'ld invoke make(1) as:

    % make -DFOO -DBAR wibble

or define FOO and BAR in the shell environment, which make(1) should pick
up.

	Cheers,

	Matthew

-- 
Dr Matthew J Seaman MA, D.Phil.                   7 Priory Courtyard
                                                  Flat 3
PGP: http://www.infracaninophile.co.uk/pgpkey     Ramsgate
                                                  Kent, CT11 9PW

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 259 bytes
Desc: OpenPGP digital signature
Url : http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20091230/b3758ecf/signature.pgp


More information about the freebsd-questions mailing list