如何使用makefile包含C中另一个目录中的.a静态库和.h文件? [英] how to use makefile to include .a static library and .h file from another directory in C?
问题描述
我创建了一个.h
头文件,实现并创建了.a
静态库文件,它们都位于/home/data/folder1
的目录中.
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
.
我还有另一个.c
文件,它将使用链接.h
头文件和.a
库文件.但是,.c
文件位于目录/home/data/folder2
中.
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
.
我应该在Makefile(也位于/home/data/folder2
中)中写些什么?另外,我应该在要编译的.c
文件中包含myheader.h
吗?到目前为止,这是我目前无法使用的内容:
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
现在,GCC需要知道在哪里查找标头,因此我们只需将其包含在CFLAGS
中.链接器(不是编译器)需要知道在哪里寻找库,因此我们可以将其添加到LDFLAGS
:
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)
如果未明确运行GCC,它将自动使用CFLAGS
和LDFLAGS
.
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
链接器将在LDFLAGS
的-L
选项命名的所有目录中寻找libmylib.a
.
The linker will look for libmylib.a
in all of the directories named by the -L
options in LDFLAGS
.
由于main
和main.o
的规则是明确的,因此应进行更改(但请务必使用制表符,而不是4个空格):
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 $@
这篇关于如何使用makefile包含C中另一个目录中的.a静态库和.h文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!