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.
Solution. First, create a makefile in the directory where you want your static library to be created, and declare a phony target all whose single prerequisite is the static library. Next, declare your static library target.
Static linking means that the code for all routines called by your program becomes part of the executable file. Statically linked programs can be moved to run on systems without the XL C/C++ runtime libraries.
Makefile is a set of commands (similar to terminal commands) with variable names and targets to create object file and to remove them. In a single make file we can create multiple targets to compile and to remove object, binary files. You can compile your project (program) any number of times by using Makefile.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With