How to use external libraries and headers in C Makefile?

♀尐吖头ヾ 提交于 2021-02-07 08:19:31

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/15045748/how-to-use-external-libraries-and-headers-in-c-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!