I have a C project that won't link correctly, and I suspect it's because of the --as-needed flag passed to the ld program by gcc. Because of that flag, gcc sees any linked library listed as an option before the *.c files as unnecessary, and won't link them.
PREFIX?=/usr/local
CFLAGS=-D_LARGEFILE64_SOURCE=1 -g -Wall -I${PREFIX}/apr/include/apr-1 -I${PREFIX}/apr/include/apr-util-1
LDFLAGS=-lapr-1 -pthread -laprutil-1
all: devpkg
devpkg: bstrlib.o db.o shell.o commands.o
install: all
install -d $(DESTDIR)/$(PREFIX)/bin/
install devpkg $(DESTDIR)/$(PREFIX)/bin/
clean:
rm -f *.o
rm -f devpkg
rm -rf *.dSYM
When I run this makefile I get the following.
cc -D_LARGEFILE64_SOURCE=1 -g -Wall -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-util-1 -c -o bstrlib.o bstrlib.c
cc -D_LARGEFILE64_SOURCE=1 -g -Wall -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-util-1 -c -o db.o db.c
cc -D_LARGEFILE64_SOURCE=1 -g -Wall -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-util-1 -c -o shell.o shell.c
cc -D_LARGEFILE64_SOURCE=1 -g -Wall -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-util-1 -c -o commands.o commands.c
cc -D_LARGEFILE64_SOURCE=1 -g -Wall -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-util-1 -lapr-1 -pthread -laprutil-1 devpkg.c bstrlib.o db.o shell.o commands.o -o devpkg
/tmp/ccZcAm9b.o: In function `main':
/home/zach/Desktop/devpkgzed/devpkg.c:14: undefined reference to `apr_pool_initialize'
/home/zach/Desktop/devpkgzed/devpkg.c:15: undefined reference to `apr_pool_create_ex'
/home/zach/Desktop/devpkgzed/devpkg.c:29: undefined reference to `apr_getopt_init'
/home/zach/Desktop/devpkgzed/devpkg.c:31: undefined reference to `apr_getopt'
My issue is that I don't really understand how make
is coming up with these commands via the CFLAGS that are set. How can I get the linker options to follow the compilation part instead of the other way around, which is triggering this issue?
Make has built-in rules to compile source files and link executables and libraries. The commands you list are produced by these rules.
The reason this fails for you is that, when linking, libraries should be listed after object files, because the linker does a single pass through its arguments and will discard any symbols that are not unresolved at the time they are seen. To correct it, put your libraries in the LDLIBS
variable, not the LDFLAGS
variable (i.e. just replace LDFLAGS
by LDLIBS
). The LDFLAGS
variable is meant for non-library options for the linker, such as -L
or -shared
etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With