Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

makefile for creating (.so) file from existing files

I have 4 files: 1.c, 1.h, 2.c, 2.h. I need a makefile, which will create a dynamic library (.so) from those 4 files. I have tried to write a makefile like this:

library.so : 1.c 1.h 2.c 2.h

but it did not work. It would be great, if someone helps me, thanks.

like image 359
user2581733 Avatar asked Nov 01 '14 13:11

user2581733


2 Answers

Something like

 CC=gcc
 CFLAGS= -Wall -g -O -fPIC
 RM= rm -f
 .PHONY: all clean

 all: library.so
 clean:
      $(RM) *.o *.so

 library.so: 1.o 2.o
      $(LINK.c) -shared $^ -o $@

 1.o: 1.c 1.h 2.h

 2.o: 2.c 1.h 2.h

But this is untested! I am assuming Linux with GNU make, and a directory containing only the source code of your library (with the above Makefile), which might be bad practice -you might want a test case- (you could have a special Makefile rule for %.pic.o depending on %.c, etc...)

Hints: use make -p to understand the builtin rules. Then make --trace or (with remake) remake -x to understand a bit more what make is doing.

Read also Drepper's paper: How to Write Shared Libraries, documentation of GNU make, Program Library HowTo, this answer, ...

like image 123
Basile Starynkevitch Avatar answered Oct 25 '22 16:10

Basile Starynkevitch


The simplest way is:

CXXFLAGS += -fPIC
CXXFLAGS += -O3
x.so: 1.o 2.o
    $(LINK.cc) -shared $^ $(LOADLIBS) $(LDLIBS) -o $@

Slightly more advanced:

CC    = gcc
FLAGS        = # -std=gnu99 -Iinclude
CFLAGS       = -fPIC -g #-pedantic -Wall -Wextra -ggdb3
LDFLAGS      = -shared

DEBUGFLAGS   = -O0 -D _DEBUG
RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program

TARGET  = example.so
SOURCES = $(wildcard *.c)
HEADERS = $(wildcard *.h)
OBJECTS = $(SOURCES:.c=.o)


all: $(TARGET)

$(TARGET): $(OBJECTS)
        $(CC) $(FLAGS) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) $(OBJECTS)
like image 30
4pie0 Avatar answered Oct 25 '22 17:10

4pie0