Wednesday, September 14, 2011

A very simple gcc makfile for Creating and Linking a static C lib on Windows

The short makfile script below is to create and use a static c lib in gcc compiler for C code.


Requirement:
1. gcc compiler (e.g. cygwin);
2. Put in a folder the following files:
   main.c //main program, to call mylib.lib
   mylib.c //lib's src, to generate mylib.lib
   mylib.h //lib's hearder
   makefile


makefile:
#my library
LIB_SRC = mylib.c
LIB_DEP = $(LIB_SRC:.c=.h)
LIB_OBJ = $(LIB_SRC:.c=.o)
LIB = $(LIB_SRC:.c=.lib)
#main program
SRC = main.c
BIN = main.exe
# include directories
INCLUDES = -I.
# compiler
CC = gcc
# dependency
$(BIN): $(LIB) $(SRC)
$(CC) -o $(BIN) $(SRC) $(LIB)
$(LIB): $(LIB_OBJ)
ar rcs $(LIB) $(LIB_OBJ)
$(LIB_OBJ): $(LIB_SRC) $(LIB_DEP)
$(CC) -c -o $@ $< $(INCLUDES)
clean:
rm -f $(LIB_OBJ) $(LIB) $(BIN)


Add tab before for each command line.


Usage:
To run on a UNIX-like command line tool in Windows:
$ make
or
$ make main.exe
will compile and generate both mylib.lib and main.exe
$ make mylib.lib
will compile and generate only mylib.lib


For more info: GNU `make`

No comments:

Post a Comment

(Coding && Eating) || Sleeping