I have created a .h header file, implemented and created .a static library file, both of them are in directory in say, /home/data/folder1.
I have another .c file which will use link the .h header file and the .a library file. However, the .c file is in directory /home/data/folder2.
What should I write in the Makefile (which is also located in /home/data/folder2)? Also, should I include myheader.h in the .c file that I want to compile? Here is what I have so far, but not working:
LIBB = -L/home/data/folder1/libmylib.a
HEADER = -L/home/data/folder2/myheader.h
main: main.o
gcc $(HEADER) $(LIBB) $< -o $@
main.o: main.c
gcc -c main.c
.PHONY: clean
clean:
rm -f *.o *.~ a.out main
Any help will be appreciated, thanks in advance!
Including header files and libraries from non-standard directories is simple.
You have the path to the directory containing the library and the one containing the header, so we store those in variables:
LIBB = /home/data/folder1
LIBINCLUDE = /home/data/folder2
Now GCC needs to know where to look for headers, so we simply include it in the CFLAGS. The linker (not the compiler) needs to know where to look for libraries, so we can add that to LDFLAGS:
CFLAGS += -I$(LIBINCLUDE)
LDFLAGS += -L$(LIBB)
It will use the CFLAGS and LDFLAGS automatically if you don't explicitly run GCC.
But for the link step, it needs to know that the library is needed, so:
LDFLAGS += -static -lmylib
The linker will look for libmylib.a in all of the directories named by the -L options in LDFLAGS.
Since your rules for main and main.o are explicit, change them like so (but be sure to use a tab, not 4 spaces):
main: main.o
gcc $(LDFLAGS) $< -o $@
main.o: main.c
gcc $(CFLAGS) $< -o $@
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