I have a header file myheader.h and a static library libmylib.a file in directory1. In directory2, I'm writing a program which uses them. Suppose I have main.c in directory2 which uses myheader.h and libmylib.a. How do I create a Makefile to compile and link them?
Right now, in my main.c, I have added
#include "../directory1/myheader.h"
Here's my Makefile at the moment:
CC = gcc
INCLUDES = -I
CFLAGS = -g -Wall $(INCLUDES)
main: main.o ../directory1/libmylib.a
$(CC) main.o ../directory1/libmylib.a -o main
main.o: main.c ../directory1/myheader.h
$(CC) $(CFLAGS) -c main.c
I'm getting the following warning:
gcc -g -Wall -I -c main.c
/home/me/directory2/main.c:72: undefined reference to `foo'
collect2: ld returned 1 exit status
make: *** [main.o] Error 1
where foo is one of the functions in the library.
Ok. Fixed it.
I removed #include "../directory1/myheader.h"
and replaced it with #include "myheader.h"
.
Then in the Makefile, I used:
CC = gcc
INCLUDES = -I../directory1
CFLAGS = -g -Wall $(INCLUDES)
LDFLAGS = -L../directory1
main: main.o ../directory1/libmylib.a
$(CC) main.o $(LDFLAGS) -lmylib -o main
main.o: main.c ../directory1/myheader.h
$(CC) $(CFLAGS) -c main.c
Using -lmylib
will be a problem. For non-static libraries you would need to fiddle with the variable LD_LIBRARY_PATH; see Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?. You could fix your makefile by adding -L ../directory1
. But the simplest thing is just replace -lmylib
with ../directory1/libmylib.a
.
For example:
directory1/mylib.c
#include "../directory1/myheader.h"
void foo(void) {}
directory1/Makefile
libmylib.a: mylib.o
ar r $@ $?
directory1/main.c:
#include "../directory1/myheader.h"
int main(void) {
foo();
return 0;
}
directory1/Makefile
main: main.o ../directory1/libmylib.a
gcc main.o ../directory1/libmylib.a -o main
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