C: Creating static library and linking using a Makefile

user3337714 picture user3337714 · Jul 15, 2015 · Viewed 61.4k times · Source

I am trying to understand static and shared Libraries.

I want to do the following to create a makefile that does separate compilation and linking such that a static library is created and linked in forming the final static executable.

I have the following code for the Makefile, but I am getting the following error

Makefile:13: *** missing separator. Stop.

But I am also trying to understand how to actually link/create libraries.

If I run the commands after line 12 in the terminal they work, but not in the makefile.

myProgram: main.o addSorted.o freeLinks.o
    gcc -lm -o myProgram main.o addSorted.o freeLinks.o

main.o: main.c
    gcc -O -c -lm main.c main.h

addSorted.o: addSorted.c addSorted.h
    gcc -O -c -lm addSorted.c

freeLinks.o: freeLinks.c freeLinks.h
    gcc -O -c -lm freeLinks.c

ar rc libmylib.a main.o addSorted.o freeLinks.o    //Error Line

ranlib libmylib.a

gcc -o foo -L. -lmylib foo.o

clean:
    rm -f myProgram main.o addSorted.o freeLinks.o

Also, if you can assist in improving the code, I would really appreciate it.

Answer

Sergey picture Sergey · Jul 15, 2015

Try this:

all: myProgram

myProgram: main.o libmylib.a #libmylib.a is the dependency for the executable
        gcc -lm -o myProgram main.o -L. -lmylib

main.o: main.c
        gcc -O -c main.c main.h

addSorted.o: addSorted.c addSorted.h
        gcc -O -c addSorted.c

freeLinks.o: freeLinks.c freeLinks.h
        gcc -O -c freeLinks.c

libmylib.a: addSorted.o freeLinks.o #let's link library files into a static library
        ar rcs libmylib.a addSorted.o freeLinks.o

libs: libmylib.a

clean:
        rm -f myProgram *.o *.a *.gch #This way is cleaner than your clean

This set of rules first compiles all files, then it makes library (libmylib.a) target and uses it's artifact to link the executable. I also added separate redundant target form making libs only. Needed files:

user@host> ls
addSorted.c  addSorted.h  freeLinks.c  freeLinks.h  main.c  main.h Makefile