Now its time to go into the useful stuff. This tutorial requires more files in order to understand how it works.
That means we need to change some things...
your folder name
makefile
prog.c
foo.c
First we start with the c-files:
prog.c
/* Simple C-program */
#include <stdio.h>
//Header to the function from foo.c
int foo(int,int);
int main()
{
printf("3+2=%d\n",foo(3,2));
return 0;
}
foo.c
int foo(int a,int b)
{
return a+b;
}
Change the contents of the makefile to this:
#Another simple makefile.
CC = gcc
PROGRAM = prog
SRCS = $(wildcard ./*.c)
#simplified version of: $(patsubst %.c,%.o,$(SRCS))
OBJS = $(SRCS:%.c=%.o)
all: $(PROGRAM)
$(PROGRAM): $(OBJS)
$(CC) $^ -o $@
%.o: %.c
$(CC) $< -c -o $@
run: all
./$(PROGRAM)
clean:
rm $(OBJS)
%.print:
echo $*
As with $@ and $<, $^ and $* works similarly
To test $* I made a test just for that. Try to run for example:
make hello_im_testing_this.print
It should return:
echo hello_im_testing_this
hello_im_testing_this
Before we get into how %.o: %.c is working we need to check the line with: SRCS = $(wildcard ./*.c). $(something var1,var2) is a built-in function, and the wildcard function communicates with the outside world and tries to find all files matching a certain pattern. In this case it searches for files in this directory ending with .c. This means that it should find prog.c and foo.c. As with bashscript it will return the value in a array, or:
prog.c foo.c
The next value will use another common makefile function: patsubst, but this is the lazy version. This line will change all .c files in the array to .o. Now we have a fresh variable $(OBJS) with:
prog.o foo.o
So when we run make run it should be executed in this order:
Instead of %.o:%.c its common to write .c.o:, which does pretty much the same. However i recommend to use %.o:%.c because its usable for other languages, which u may not know about, such as %.html:%.php for example (even if its possible to make your own .php.html:,although more complicated to do).