Link Static/Dynamic Library in C/C++ on Linux

 C++
 

Note about link library in C/C++.

Static Library

A static library is basically an archive (like a zip file) of object files, which are compiled from the .c/.cpp source code.

Compile files into *.o object files.

1
gcc -c test1.cpp test2.cpp

(The -c switch means: Compile and assemble, but do not link.)

Thus, we get two files test1.o and test2.o.

Now, we can use ar to put these object files together into a single static library.

1
ar rsv testlib.a test1.o test2.o

Now the testlib.a contains test1.o and test2.o.

1
gcc -o test.out test.c testlib.a

Alternatively, you could use the explicity linking options to link the static library (-L switch specifies the static library path and -l followed by the name of the static library):

1
gcc -o test.out test.c -L. -ltestlib

The static library is distributed with a function declaration header files .h, so that you know how to invoke them and the compiler takes care of them e.g. linking .a static libraries into your executables.

The Dynamic Link Library (DLL) is stored separately from the target application and shared among different applications, compared to Static Library. The DLL is the file extension on Windows while on Linux, it is *.so (Shared Object).

The .so/.dll can be loaded right before the application starts or during the application’s runtime. On Windows, the Win32 API LoadLibrary is used while on Linux gcc compiler, the dlopen function is used.

1
gcc -shared -o libhello.so -fPIC hello.c

Another example:

1
g++ Application.cpp -o Application -I/home/wjw/dev/Youtube/OpenGL/Dependencies/GLFW/include -L/home/wjw/dev/Youtube/OpenGL/Dependencies/GLFW/lib -lglfw

(Where shared library is called libglfw.so)
(Note: You should also do

1
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/dev/Youtube/OpenGL/Dependencies/GLFW/lib

)

Calling C++ Shared Library from Python Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// https://helloacm.com
extern "C"
{
// A function adding two integers and returning the result
int SampleAddInt(int i1, int i2)
{
return i1 + i2;
}

// A function doing nothing ;)
void SampleFunction1()
{
// insert code here
}

// A function always returning one
int SampleFunction2()
{
// insert code here

return 1;
}
}

Compile it as Shared Library:

1
g++ -Wall -O3 -shared TestLib.c -o TestLib.so

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/python

import ctypes

def main():
TestLib = ctypes.cdll.LoadLibrary('/home/wjw/misc/cpp_static_dynamic_lib/TestLib.so')
print(TestLib.SampleAddInt(1, 2))

if __name__ == '__main__':
main()

References

How to Link Static Library in C/C++ using GCC Compiler
How to Use the Dynamic Link Library in C++ Linux (gcc compiler)
Calling C++ Shared Library from Python Code (Linux Version)