0

I have have four files a.c b.c c_arm.c and header file header.h I have written a make file, but when do just make and execute the binary it should print I am in c-arm but when i do make ARM=arch and when i execute the final binary file, it should print I am in c-armx86

But in my case it always prints I am in c-arm

Can you please tell how to write a make file do achieve the above things, here are my files

a.c

#include "header.h"
int main () {
   call_b();
}

b.c

#include "header.h"

void call_b()    {
#ifdef ARCH
  carmx86();
#else
  carm();
#endif
}

c_arm.c

#include "header.h"
carm() {
    printf ("I am in c-arm\n");
}

c_armx86.c

#include "header.h"
void carmx86() {
    printf( "I am in c-armx86 \n" );
}

Makefile 

all: a.o b.o c_arm.o c_armx86.o
  gcc -o output a.o b.o c_arm.o c_armx86.o

a.o: a.c
  gcc -c a.c

b.o: b.c
  gcc -c b.c

c_arm.o: c_arm.c
  gcc -c c_arm.c

c_armx86.o: c_armx86.c
  gcc -c c_armx86.c

clean:
  rm *.o output

when i say make ARCH=arm it should print I am in c-armx86, if i just do a make and execute binary it should print I am in c-arm

can anyone tell how can i do this ?

2
  • @Orbit oops.. slip of finger.. :)
    – Dipto
    Feb 28, 2014 at 10:25
  • OK I added a blank header.h so it didn't 'make' a difference. No more C jokes, I am sorry. Feb 28, 2014 at 10:25

1 Answer 1

1

You need to pass -D ARCH=arm to compiler i.e.:

ifdef ARCH
b.o: b.c
      gcc -D ARCH=$(ARCH) -c b.c
else
b.o: b.c
      gcc -c b.c
endif

or equivalent:

b.o: b.c
ifdef ARCH
      gcc -D ARCH=$(ARCH) -c b.c
else
      gcc -c b.c
endif
3
  • That worked for me :-) don't make the same mistake as me and forget to "make clean" after updating the Makefile. Feb 28, 2014 at 10:23
  • @user2672165 : Now its printing only I am in c-armx86 Feb 28, 2014 at 11:34
  • I have updated my answer to not always define ARCH. It could be rewritten so that the conditionals are applied below one single rule. Feb 28, 2014 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.