2

My Makefile was like this earlier.

export SOURCE1 = source1.c \
        1.c \
        2.c \
        3.c 

export SOURCE2 = source2.c \
        1.c

all:
    gcc -Wall -W -g -O2 ${SOURCE1} -lm -lipc -o source1
    gcc -Wall -W -g -O2 ${SOURCE2} -lm -lipc -o source2

This one works fine. And, I wanted to create a shared object which comprises 1.c, 2.c and 3.c. Consequently I changed my Makefile to

export LIB_SOURCE 1.c 2.c 3.c

export SOURCE1 = source1.c 

export SOURCE2 = source2.c 

all:
    gcc -Wall -W -g -O2 ${LIB_SOURCE} -o libsrc.so.1
    ln -sf libsrc.so.1 libsrc.so.0
    ln -sf libsrc.so.0 libsrc.so

    gcc -Wall -W -g -O2 ${SOURCE1} -lm -lipc -lsrc -o source1
    gcc -Wall -W -g -O2 ${SOURCE2} -lm -lipc -lsrc -o source2

The make failed while compiling source2, saying it

src.so: undefined reference to 'var1'

The var1 is defined in 3.c which is not needed by source2. Since it's included in the library it's failing looking at it. How to move on with this error.

Thanks,

user1293997
  • 855
  • 5
  • 12
  • 20
  • I do not know if it is the solution, but try to add the `-fPIC` flag for `gcc` This option is needed to build shared libraries. See http://stackoverflow.com/questions/5311515/gcc-fpic-option – francis Jan 09 '14 at 22:58

1 Answers1

1

I was able to get your makefile to work with a couple of small adjustments:

all:
    gcc -Wall -W -g -O2 -shared ${LIB_SOURCE} -o libcsrc.so
    gcc -Wall -W -g -O2 -L. ${SOURCE1} -lm -lsrc -o source1
    gcc -Wall -W -g -O2 -L. ${SOURCE2} -lm -lsrc -o source2

(I removed -lipc because I don't have that library handy.) But I suggest a slightly different approach once the above is working perfectly for you. Since you are constructing the library libsrc.so, make a separate rule for it, and a separate rule for each of the executables, and use prerequisite lists:

all: source1 source2

source1: source1.c libcsrc.so
    gcc -Wall -W -g -O2 -L. source1.c -lm -lsrc -o source1

source1: source2.c libcsrc.so
    gcc -Wall -W -g -O2 -L. source2.c -lm -lsrc -o source2

libcsrc.so: ${LIB_SOURCE}
    gcc -Wall -W -g -O2 -shared ${LIB_SOURCE} -o libcsrc.so

Then you can put in automatic variables, and combine the source1 and source2 rules:

all: source1 source2

source1 source2: % : %.c libcsrc.so
    gcc -Wall -W -g -O2 -L. $< -lm -lsrc -o $@

libcsrc.so: ${LIB_SOURCE}
    gcc -Wall -W -g -O2 -shared $^ -o $@
Beta
  • 96,650
  • 16
  • 149
  • 150