# Link a static/ archive file with code in GCC/ G++

Get FREE domain for 1st year and build your brand new site

To link a static or archive library file during compilation using GCC or G++, simply mention the static library (.a file) in the compilation command.

g++ -std=c++14 code.cpp lib/static_library.a


This will result in a single executable a.out with the executable of 2 code files:

• code.cpp
• lib/static_library.a

Learn how to create an archive library

In case of multiple archive libraries, we will list all library files at the end of the compilation process. This will merge all

g++ -std=c++14 code.cpp lib/static_library.a
lib/static_library2.a
lib/opengenus.a


This will result in a single executable a.out which will have the executable of 4 code files:

• code.cpp
• lib/static_library.a
• lib/static_library2.a
• lib/opengenus.a

This is in contrast with the case of shared library where we need to follow multiple steps:

For shared object library, we need to follow the following steps:

# Create the executable by linking shared library
gcc -L<path to .SO file> -Wall -o code main.c -l<library name>

# Make shared library available at runtime
export LD_LIBRARY_PATH=<path to .SO file>:\$LD_LIBRARY_PATH

# Run executable
./a.out


Hence, archive library is much simple to use and share as we need to handle only one executable and it does not depend on the location of libraries or setting environment variables like LD_LIBRARY_PATH.

Create an archive library and link it.