Reputation: 4571
I would like to compile .c files to a .so (shared library). And I don't understand why, I have that makefile that makes me an error:
LIB = libmy.so
SRC = lib.c
CC = gcc
OBJ = $(CC) -c -fPIC $(SRC)
all: $(LIB)
re: fclean all
$(LIB): $(OBJ)
$(CC) -shared -fPIC $(OBJ) -o $(LIB)
clean:
$(RM) $(OBJ)
fclean: clean
$(RM) $(LIB)
Thanks in advance for helping.
Upvotes: 0
Views: 3864
Reputation: 4571
That works :
LIB = libmy.so
SRC = lib.c
CC = gcc
OBJ = $(SRC:.c=.o)
all: $(LIB)
re: fclean all
$(LIB):
$(CC) -c -fPIC $(SRC)
$(CC) -shared -fPIC $(SRC) -o $(NAME)
clean:
$(RM) $(OBJ)
fclean: clean
$(RM) $(LIB)
I just need OBJ = $(SRC:.c=.o)
in fclean
Upvotes: 0
Reputation: 15776
The problem is in the following line:
$(LIB): $(OBJ)
When expanded this becomes:
libmy.so : gcc -c -fPIC lib.c
Hence the error.
What you probably wanted was :
OBJ = lib.o
To save you having to manually convert all .c
source files to .o
you can use a rule like this instead of OBJ = lib.o
:
OBJ = $(SRC:%.c=%.o)
This creates a variable OBJ
containing a list of all the files in SRC
with any .c
extension changed to .o
. eg. If we had SRC = foo.c bar.c
then the rule above would automatically expand to:
OBJ = foo.o bar.o
Upvotes: 5
Reputation: 169793
$(LIB): $(OBJ)
expands to
libmy.so: gcc -c -fPIC $(SRC)
ie you put your recipe into the depency list, and make rightfully complains.
Personally, I'd write the makefile like this:
CC := gcc
RM := rm -f
LIB := libmy.so
OBJ := lib.o
GARBAGE := $(OBJ)
.PHONY: all clean realclean
all: $(LIB)
$(LIB): LDFLAGS += -shared
$(LIB): $(OBJ)
$(CC) $(LDFLAGS) -o $@ $<
$(OBJ): CFLAGS += -fPIC
$(OBJ): %.o : %.c
$(CC) $(CFLAGS) -c -o $@ $<
realclean: GARBAGE += $(LIB)
clean realclean:
$(RM) $(GARBAGE)
Note that your original version did not contain a rule to make $(OBJ)
. If you wanted to use the implicit one, you would need to add -fPIC
to CFLAGS
.
Upvotes: 0