First, avoid naming your executable test
since it is a standard program name (at least on POSIX).
Then, read documentation of GNU make. It contains a tutorial section.
At last, GNU make has several built-in rules, which you can get with make -p
See this answer for an example.
I strongly recommend compiling with all warnings and debug info (that is, with gcc -Wall -Wextra -g
if using GCC). So put CFLAGS+= -Wall -Wextra -g
and CC=gcc
in your Makefile
.
To link with your -lcjson
add LIBES+= -lcjson
in your Makefile
. Remember that tab characters are important in a Makefile
(so use some editor, e.g. emacs
, able to edit them).
So try:
# your Makefile, replace four spaces with tab
CC= gcc
CFLAGS+= -Wall -Wextra -g
RM= rm -f
MY_SOURCES=$(wildcard *.c)
## above could be an MY_SOURCES= file1.c file2.c otherfile.c
MY_OBJECTS=$(patsubst %.c,%.o,$(MY_SOURCES))
#
LIBES= -lcjson
#
.PHONY: all clean
##
all: myprog
##
clean:
$(RM) myprog *.o *~
myprog: $(MY_OBJECTS)
Use make --trace
or remake
-x
to debug your Makefile
If you haver several *.c
source files (that is translation units) linked together into the same program, you should have a common header file myheader.h
(to share common declarations of all your public functions and variables) which should be #include
-ed in every source file. Then you need to depend on it:
MY_HEADER= myheader.h
%.o: %.c $(MY_HEADER)
Notice that (with or without any Makefile
) the order of program arguments to gcc
is very significant. See this.