Static vs Dynamic Libraries - C Programming
Creating libraries for your programs can be a useful tool to make your job as a web developer more efficient.
If you don't know already, a library in programming is a collection of prewritten code that you can use to optimize tasks. This code is usually targeted for specific common problems such as building apps and website more efficiently. It can help with user authentication, server connection, user interfaces, algorithms, data management and so much more!
Now you might be asking yourself: "but how do I create one?" Before we answer that question, we must know that there is two different types of libraries: Static and dynamic.
A static library allows us to link to the program and are not relevant during the runtime, this makes it reusable in multiple programs but it is locked into one at compile time. On the other hand, dynamic libraries are preferably used when you want to run a lot of programs at the same time that are using the same library, and you want to be more efficient with it since these are separate files outside of the executable file.
Here's how to create a static library:
ar rcs libmylib.a objfile1.o objfile2.o objfile3.o
How to use a static library:
gcc -o foo foo.o -L. -lmylib
Here's how to create a dynamic library:
领英推荐
gcc -fPIC -c objfile1.c
gcc -fPIC -c objfile2.c
gcc -fPIC -c objfile3.c
gcc -shared -o libmylib.so objfile1.o objfile2.o objfile3.o
gcc -o foo foo.o -L. -lmylib
How to use a dynamic library:
echo $LD_LIBRARY_PATH
Will display this variable if it is already defined. If it isn't, you can create a wrapper script for your program to set this variable at run-time. Depending on your shell, simply use?setenv?(tcsh, csh) or?export?(bash, sh, etc) commands. If you already have LD_LIBRARY_PATH defined, make sure you?append?to the variable. For example:
setenv LD_LIBRARY_PATH /path/to/library:${LD_LIBRARY_PATH}
would be the command you would use if you had tcsh/csh and already had an existing LD_LIBRARY_PATH. An example with bash shells:
export LD_LIBRARY_PATH=/path/to/library:${LD_LIBRARY_PATH}
Note: The LD_LIBRARY_PATH environment variable?tells the shell on Solaris systems which directories to search for client or shared IBM? Informix? general libraries. You must specify the directory that contains your client libraries before you can use the product. So in short, it specifies the search path for the library.
Useful related commands:
Happy coding!