Creating a simple Makefile to build a shared library

五迷三道 提交于 2019-12-20 08:49:08

问题


I am trying to create a very basic hand crafted Makefile to create a shared library to illustrate a point.

This is what I have so far:

SHELL = /bin/sh
CC    = gcc
FLAGS        = -std=gnu99 -Iinclude
CFLAGS       = -fPIC -pedantic -Wall -Wextra -march=native -ggdb3
DEBUGFLAGS   = -O0 -D _DEBUG
RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program

TARGET  = example.so
SOURCES = $(shell echo src/*.c)
HEADERS = $(shell echo include/*.h)
OBJECTS = $(SOURCES:.c=.o)

PREFIX = $(DESTDIR)/usr/local
BINDIR = $(PREFIX)/bin

all: $(TARGET)

$(TARGET): $(OBJECTS)
    $(CC) $(FLAGS) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) $(OBJECTS)

When I run make, it attempts to build an application - and ld fails because it can't resolve main().

Problem seems to be with CFLAGS - I have specified -fPIC but that is not working - what am I doing wrong?

Edit

I added the -shared flag as suggested, when I run make, I got this error:

gcc -std=gnu99 -Iinclude -fPIC -shared -pedantic -Wall -Wextra -march=native -ggdb3 -O0 -D _DEBUG -o example.so src/example.o
/usr/bin/ld: src/example.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
src/example.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
make: *** [example.so] Error 1

Which seems to be suggesting to revert back to -fPIC only.

BTW, my new CFLAGS setting is:

CFLAGS       = -fPIC -shared -pedantic -Wall -Wextra -march=native -ggdb3

I am running gcc v4.4.3 on Ubuntu 10.0.4.


回答1:


The solution was to modify the XXFLAGS as follows:

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



回答2:


Compile with -shared:

gcc -o libfoo.so module1.o module2.o -shared

(This also works on MingW under Windows to produce DLLs.)




回答3:


Example for C++ files. Also included a clean target

.PHONY : clean

CPPFLAGS= -fPIC -g
LDFLAGS= -shared

SOURCES = $(shell echo *.cpp)
HEADERS = $(shell echo *.h)
OBJECTS=$(SOURCES:.cpp=.o)

FIKSENGINE_LIBDIR=../../../../lib
FIKSENGINE_INCDIR=../../../../include

TARGET=$(FIKSENGINE_LIBDIR)/tinyxml.so

all: $(TARGET)

clean:
    rm -f $(OBJECTS) $(TARGET)

$(TARGET) : $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o $@ $(LDFLAGS)



回答4:


Since you try to build so file, you probably need -shared.



来源:https://stackoverflow.com/questions/8096015/creating-a-simple-makefile-to-build-a-shared-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!