Skip to content

Instantly share code, notes, and snippets.

@lixit
Created September 16, 2019 09:10
Show Gist options
  • Save lixit/e58bef38d8014db79ad7adf5c95a8a13 to your computer and use it in GitHub Desktop.
Save lixit/e58bef38d8014db79ad7adf5c95a8a13 to your computer and use it in GitHub Desktop.

Two Linux C/C++ library types 1. Static Library (.a) : become part of application 2. Dynamically linked shared object libraries (.so) : one form but can used in two ways: 1) Dynamically linked at run time 2) Dynamically loaded/unloaded and linked during execution using the dynamic linking loader system functions

Library naming convertions: libraries are typically named with prefix "lib". When linking, the command line reference will not contain the library prefix and suffix example: gcc src.c -lm -lpthread linked: /usr/lib/libm.a and /usr/lib/libpthread.a

Static libraries (.a) Compile: cc -Wall -c ctest1.c ctest2.c Create library: ar -cvq libctest.a ctest1.o ctest2.o List files in library: ar -t libctest.a Linking with the library: cc -o exectable_name prog.c libctest.a cc -o executable_name prog.c -L/path/to/library-directory -lctest

Dynamtically Linked Libraries (.so) Compile gcc -Wall -fPIC -c ctest1.c ctest2.c Create library: gcc -shared -Wl,-soname,libctest.so.1 -o libctest.so.1.0 ctest1.o ctest2.o

	mv libctest.so.1.0 /opt/lib
	ln -sf /opt/lib/libctest.so.1.0 /opt/lib/libctest.so.1
	ln -sf /opt/lib/libctest.so.1   /opt/lib/libctest.so
		note:
			The link to /opt/lib/libctest.so allows the naming convention for the compile flag -lctest to work.
			The link to /opt/lib/libctest.so.1 allows the run time binding to work. See dependency below.
Compile main program and link with shared object library:
	gcc -Wall -I/path/to/include-files -L/path/to/libraries prog.c -lctest -o prog
	gcc -Wall -L/opt/lib prog.c -lctest -o prog
Run Program:
	Set path: export LD_LIBRARY_PATH=/opt/lib:$LD_LIBRARY_PATH
	Run: prog
	
List Dependencies:
	ldd prog
		linux-vdso.so.1 (0x00007ffe30b96000)
		libctest.so.1 => /opt/lib/libctest.so.1 (0x00007fe015bbc000)
		libc.so.6 => /usr/lib/libc.so.6 (0x00007fe0159af000)
		/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fe015bc8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment