Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external libraries and headers in C Makefile?

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.

like image 721
ask Avatar asked Feb 23 '13 21:02

ask


2 Answers

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
like image 82
ask Avatar answered Oct 14 '22 15:10

ask


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
like image 33
Joseph Quinsey Avatar answered Oct 14 '22 14:10

Joseph Quinsey