5

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!

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
CTownsend
  • 51
  • 1
  • 1
  • 2

1 Answers1

8

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 $@
greyfade
  • 24,948
  • 7
  • 64
  • 80
  • Thanks! but uh...what if I have my header and the library in the same directory, while the .c file in another? should I do the same thing? at the mean time, do I have to write #include "myheader.h" in my .c file? Thanks! – CTownsend Oct 13 '13 at 03:22
  • You *may* have to add `-I.` and `-L.`, but the process is all the same. But both of the rules for `main` and `main.o` you can safely leave off the `gcc` line and it'll do the right thing. Also, yes, you *do* need to have an appropriate `#include` directive in your `.c` file. – greyfade Oct 13 '13 at 03:30