make files drastically improve the ability to reliably compile from source
[TOC]
hi.c
#include "hi.h"
int main()
{
myPrintHi(); // call a function in another file
return(0);
}
hifunc.c
#include "hi.h"
#include <stdio.h>
void myPrintHi( void )
{
printf( "Hi makefiles!\n" );
return;
}
hi.h
/* example include file */
void myPrintHelloMake( void );
gcc -o hi.exe hi.c hifunc.c -I .
output name, input files, output directory is . ./hi.exe prints Hi makefiles!
rather than copy paste a command each time to recompile, use the make shell command which uses lastmod to update
makefile
hi: hi.c hifunc.c
gcc -o hi hi.c hifunc.c -I .
note the name of the executable: sources that might change (also, there's a required TAB before the gcc command)
-
-
project layout: hi/makefile , hi/src/hi.h, hi/src/hi.c , hi/src/hifunc.c, hi/obj
the ordering in the makefile is VERY IMPORTANT (both vertically and horizantally) TAB indent is required after a rule, not spaces!
CC = gcc LIBS=-lm
EXECUTABLE=hi
all: $(EXECUTABLE)
$(EXECUTABLE): hi.o hifunc.o $(CC) $(LIBS) -o $(EXECUTABLE) hi.o hifunc.o
hi.o: src/hi.c src/hi.h $(CC) -c src/hi.c src/hi.h
hifunc.o: src/hifunc.c src/hi.h $(CC) -c src/hifunc.c src/hi.h
.PHONY: clean
clean: rm -rf .o rm -rf src/.gch rm $(EXECUTABLE)
-
Below is incorrect in that it requires the use of $< expansions...
CC = gcc
LIBS=-lm
SOURCEDIR=src
EXECUTABLE=hi
OBJDIR=obj
_OBJS = hi.o hifunc.o
OBJS = $(patsubst %,$(OBJDIR)/%,$(_OBJS))
$(OBJDIR)/%.o: $(SOURCEDIR)/%.c $(SOURCEDIR)/hi.h
$(CC) -c -o $@ $<
all: $(OBJS) $(EXECUTABLE)
$(EXECUTABLE): $(OBJS)
$(CC) $(LIBS) -o $(EXECUTABLE) $(OBJS)
.PHONY: clean
clean:
rm -rf $(OBJDIR)/*.o
rm -rf src/*.gch
rm $(EXECUTABLE)