jimi hendrix
jimi hendrix

Reputation: 2259

Problem Creating a Static Lib in Linux

I am making a simple lib to use in my apps to save me the trouble of defining some functions over and over...

Here's my makefile:

CC=gcc
CFLAGS=-Wall -g -Wextra
OBJS=getline.o debug.o
LIB=libjimi.a
.PHONY: clean purge

libjimi.so : $(OBJS)
        ar rcs $(LIB) $(OBJS)
        @echo done!
%.o : %.c
        $(CC) $(CFLAGS) -c $^

clean :
        @rm *.o

purge : clean
        @rm $(LIB)

Now I get a segfault if I link the library, but if I link the object files that I link to create the library, it works...advice?

Upvotes: 1

Views: 352

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

Static libraries on Linux (Unix) normally end with '.a'; shared objects end with '.so'. Your library rule is currently:

libjimi.so : $(OBJS)
    ar rcs $(LIB) $(OBJS)
    @echo done!

It should be:

$(LIB): $(OBJS)
    ar rcs $(LIB) $(OBJS)
    @echo done!

Personally, I tend to use

AR      = ar
ARFLAGS = rv

Leading to:

$(LIB): $(OBJS)
    $(AR) $(ARFLAGS) $(LIB) $(OBJS)

Now all aspects of the build can be tuned by setting macros - if necessary.

Without knowing where the crash is occurring, it is hard to know what might be causing it. One possibility is that because of the makefile confusion, you are linking with an old version of the library and not with the current working version.

Incidentally, it is not nice to conceal what a clean or purge target is doing; it is much better to let make echo the commands (no @ in front). The @ is entirely appropriate for the echo though; its absence would lead to the same information being presented twice.

Upvotes: 1

Zitrax
Zitrax

Reputation: 20246

Your target say libjimi.so which is the extension for a shared library, it should just be libjimi.a for a static lib.

And note that when you use a static lib you just link it in like any other object file, but with a shared lib you use the -l syntax.

Upvotes: 2

Related Questions