I've got a Makefile.mak where I optionally create a test.exe or a DLL from my C-based source code. I'm using CL.EXE and NMAKE.
I'd like to modify my CFLAGS macro like this when the target is TEST.EXE:
CFLAGS = $(CFLAGS) -DMAIN
And, of course, I use this in my C code:
#ifdef MAIN
... int main()... yada yada
#endif
I had tried
!IF $@ == "test.exe"
but it crashed out and doesn't work logically since the $@, target, isn't deterministic in that part of the makefile.
The logical place to define the additional macro is when defining the target but I don't see how to do that without NMAKE interpreting it as DOS command.
test.exe: test.obj
CFLAGS = $(CFLAGS) -DMAIN
$(LINKER) /out:$@ $(LIB) $*.obj $(LIBS)
It'd be easier with gmake, I know. I don't have that option.
I will present two solutions: one which does what you request, namely modifying
CFLAGSbased on the target, and a second one which may be a better approach.Suppose you have a file
multiply.c:which you would like to add to a static library
my_lib.lib, and also use as a stand-alone unit test.One standard way of adding
-DMAINtoCFLAGSis to use NMAKE recursively. The second invocation of NMAKE could use a different makefile or, as as presented here, use the same makefile with a flag to prevent an infinite recursive loop.If
RECURSEis defined, the built-in rule is used to create the test programmultiply.exe.This solution works. But it requires that
multiply.objbe remade every time it is used, because there are two versions of it floating around: one with amainand one without.The second solution distinguishes between these object files.
This gives:
Trying to create a
.exefile directly from the.cfile, as in:does not work, because this still creates a
.objfile which clobbers the other version.Edit:
.SUFFIXES: .TEST_objdoes not seem to be needed.