Description of Problem: A shared library that uses the stat, fstat etc.functions provided by libc is compiled without optimization enabled and without explicitly linking to -lc. When a binary is compiled using the above shared library, the binary fails to run. Following is the error message: statest1_g: error while loading shared libraries: /samples/redhat/statest/libstatdll1_g.so: undefined symbol: stat The binary runs fine when compiled using a shared library which is compiled with either optimization enabled or explicitly linking to -lc. Version-Release number of selected component (if applicable): libc comes with Redhat Linux 7.2 How Reproducible: It happens consistently. Here is the sample: 1. statest.c #include <stdio.h> extern int foo(); int main() { printf("From main\n"); foo(); } 2. statdll.c #include <stdio.h> #include <sys/stat.h> int foo() { struct stat buf; stat("./statest.c", &buf); printf("Called stat\n"); return; } 3. statdll_g.c #include <stdio.h> #include <sys/stat.h> int foo() { struct stat buf; stat("./statest.c", &buf); printf("Called stat\n"); return; } 4. makefile all: libstatdll.so libstatdll1.so statest statest1 libstatdll_g.so libstatdll1_g.so statest_g statest1_g statdll.o: statdll.c cc -O -c statdll.c statdll_g.o: statdll_g.c cc -g -c statdll_g.c libstatdll.so: statdll.o ld -shared -o libstatdll.so statdll.o -lc libstatdll1.so: statdll.o ld -shared -o libstatdll1.so statdll.o libstatdll_g.so: statdll_g.o ld -shared -g -o libstatdll_g.so statdll_g.o -lc libstatdll1_g.so: statdll_g.o ld -shared -g -o libstatdll1_g.so statdll_g.o statest_g: statest.c cc -g -o statest_g statest.c -L./ -lstatdll_g statest1_g: statest.c cc -g -o statest1_g statest.c -L./ -lstatdll1_g statest: statest.c cc -O -o statest statest.c -L./ -lstatdll statest1: statest.c cc -O -o statest1 statest.c -L./ -lstatdll1 clean: rm -f *.o *.so statest statest1 *_g Steps to Reproduce: 1. Build the sample: go to the sample directory, run "make" 2. Set environment variable LD_LIBRARY_PATH to include the sample directory 3. Run "statest" "statest1" "statest_g" and "statest1_g" respectly. Actual Results: The first three binaries works fine. statest1_g fails. Expected Results: All four binaries should work. Additional Information: If I have to explicitly link to -lc, what's the impact to my shared library and binary?
Created attachment 46380 [details] tar'ed and gzip'ed source files to reproduce the problem
You should never use ld -shared directly to build shared libraries, unless you know exactly what consequences it has. gcc -shared will work properly.