In: Computer Science
IN C PROGRAMMING LINUX how to use makefile to include .a static library and .h file from another directory in C? 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? LIBB = -L/../directory1/libmylib.a HEADER = -L/../directory1/myheader.h main: main.o gcc $(HEADER) $(LIBB) main.o: main.c gcc -c main.c .PHONY: clean
clean: rm -f *.o *.~ a.out main
Inside the code of main.c is
#include
#include "basic.h"
int main()
{
printf("Addition: %d",add(12,23));
printf("\n Substraction: %d",sub(123,23));
return 0;
}
A) To include .a static library from another directory in C :-
To use a Library that is not linked into your program by the compiler:- 1) include the library's header file in your C source file .(eg below test.c) 2) Tell the compiler to link in the code from the library .o file into your executable file:- STEPS:- i) Add an include line (#include EG-> "somelib.h") in a program source file. ii) Link the program's .c file with the library object file (i.e. specify the somelib.o file as a command line argument to gcc) EG -> -> % gcc -o myprog test.c somelib.o iii) The resulting executable file (myprog) will contain machine code for all the functions defined in test.c plus any mylib library functions that are called by.
B) To include .h file from another directory in C :-
-> gcc -IC
main.c
where -I
option adds your C
directory to the list of
directories to be searched for header files, so you'll be
able to use #include "myheader.h"
anywhere
in your program.
You can either add a -I
option to the command line
to tell the compiler to look there for header files. If you have
header files in include/
directory, then this command
should work for you.
-> gcc
-Iinclude/
Since, you are using makefile
, you can include this
option in CFLAGS
macro in your makefile.
CFLAGS
= -Iinclude/ -c -Wall
OR
You can include header files using #include
"../include/header.h"
.