1
votes

So I am trying to learn how makefiles work to compile programs in c, But I can’t define something using gcc and main.o as “OBJS” I have this simple main function and makefile in which I try to define test

main.c

#include <stdio.h>

int main(){
    #ifdef test
        printf("ok\n");
    #else 
        printf("not ok\n"); 
    #endif

    return 0;
}

makefile

MODULES = ../
OBJS = main.o
CFLAGS = -g -Wall
PROGRAM = defineprog

$(PROGRAM): clean $(OBJS)
    gcc -D test $(OBJS) -o $(PROGRAM)

clean:
    rm -f $(PROGRAM) $(OBJS)

run: $(PROGRAM)
    ./$(PROGRAM)

Every time I compile my program and then execute it I always get the output "not ok" which means that test is not defined, does anyone know how to make this work using the main.o as “OBJS”. Thanks

1
$(PROGRAM): clean $(OBJS) makes no sense. You're telling make that your program depends on both creating all object files ($(OBJS)) and deleting all object files (clean). - melpomene
-D test is a preprocessor option. It doesn't do anything when you call gcc on object files. (This has nothing to do with make.) - melpomene

1 Answers

1
votes

You need the define for the command that does the compilation not linking.

In your setup that command is implicit (found in Make's database as a rule for creating *.o files out of *.c files) but it does use the CFLAGS Make variable, so what you can do is add -Dtest to your CFLAGS Make variable:

OBJS = main.o
CFLAGS = -Dtest -g -Wall
PROGRAM = defineprog

$(PROGRAM): $(OBJS)
    gcc -D test $(OBJS) -o $(PROGRAM)

clean:
    rm -f $(PROGRAM) $(OBJS)

run: $(PROGRAM)
  ./$(PROGRAM)