Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I compile and link with unneeded libraries in GCC?

I guess the title is slightly confusing but I will try and clarify what I mean by that. Below I have attached my make file. As you can see on the fourth line I am selecting all the libraries I want my project to link against.

When the project compiles I see that for every object file it is creating it is linking with all the libraries specified with the LIBRA line. Not all of those libraries are required by all the files in my project. Perhaps just one or two use across each .cpp file.

Does this produce any additional cost to the compilation process? Does this create a larger binary? Are modern compilers good enough that this is not a problem or do I have to read some more literature on compilers?

CC=g++
CFLAGS=-c -Wall -std=c++11 -g 
LDFLAGS+=-ldl
LIBRA= -lboost_system -lboost_filesystem -lboost_thread -lsigar-x86_64-linux -ldl -lsqlite3
LIBB=-L/home/tensai/SIGAR/lib -L/usr/include -L/usr/local/lib
SOURCES=main.cpp config_reader.cpp database_manager.cpp monitor_agent.cpp analyze_agent.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=lnmp
INCLUDES = -I/home/tensai/SIGAR

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) $(INCLUDES) $(LIBB) -o $@ $(LIBRA)

.cpp.o:
    $(CC) $(CFLAGS) $(INCLUDES) $(LIBB) $< -o $@ $(LIBRA)

clean: 
    rm *.o
like image 495
tensai Avatar asked Nov 18 '13 23:11

tensai


1 Answers

Static libraries are only pulled in if they offer symbols that are undefined at this point in the linking process. If they do not contain such symbols they are ignored. In some rare cases unnecessary libraries can still hurt, because they define symbols that are supposed to be resolved by system libraries that come later on the command line, in this case the linker takes the code from whatever library comes first. However, this is really rare.
With dynamic libraries it's different: If you feed unneeded dynamic libraries (.so) to the linker it may well put a reference to them into the executable, and you better have those libraries available at runtime. The binary don't get bigger here, but it hurts if you plan to distribute some executables separately:

$ cat x.c
int main(){return 14;}

$ gcc x.c -o xx -l ssl3 -L .

$ ./xx
./xx: error while loading shared libraries: libssl3.so: cannot open shared object file: No such file or directory

$ gcc x.c -o xx

$ ./xx

$
like image 88
pentadecagon Avatar answered Sep 29 '22 19:09

pentadecagon