user308827 user308827 - 1 month ago 8
C++ Question

Converting to makefile

gcc code.c -I/opt/local/include -L/opt/local/lib -lnetcdf -lm -fpic -o code


How can I convert this into a makefile? This is what I have right now:

IDIR =/opt/local/include
CC=gcc
CFLAGS=-I$(IDIR)

ODIR=obj
LDIR =/opt/local/lib

LIBS=-lm

code: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LIBS)

.PHONY: clean

clean:
rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~

Answer

Note that the following makefile would work

code: code.o
    gcc code.o -o code

code.o: code.c
    gcc -c code.c -I/opt/local/include -L/opt/local/lib -lnetcdf -lm -fpic

clean:
    rm *.o code

Then it's just a matter of adding variables to the makefile. For example

OBJ=code.o
CC=gcc
IDIR=/opt/local/include
LDIR=/opt/local/lib
CFLAGS=-lnetcdf -lm -fpic

code: $(OBJ)
    $(CC) $(OBJ) -o code

code.o: code.c
    $(CC) -c code.c -I$(IDIR) -L$(LDIR) $(CFLAGS)

clean:
    rm *.o code
Comments