A.1 — Static and dynamic libraries

A library is a package of code that is meant to be reused by many programs. Typically, a C++ library comes in two pieces:

1) A header file that defines the functionality the library is exposing (offering) to the programs using it.
2) A precompiled binary that contains the implementation of that functionality pre-compiled into machine language.

Some libraries may be split into multiple files and/or have multiple header files.

Libraries are precompiled for several reasons. First, since libraries rarely change, they do not need to be recompiled often. It would be a waste of time to recompile the library every time you wrote a program that used them. Second, because precompiled objects are in machine language, it prevents people from accessing or changing the source code, which is important to businesses or people who don’t want to make their source code available for intellectual property reasons.

There are two types of libraries: static libraries and dynamic libraries.

A static library (also known as an archive) consists of routines that are compiled and linked directly into your program. When you compile a program that uses a static library, all the functionality of the static library that your program uses becomes part of your executable. On Windows, static libraries typically have a .lib extension, whereas on linux, static libraries typically have an .a (archive) extension. One advantage of static libraries is that you only have to distribute the executable in order for users to run your program. Because the library becomes part of your program, this ensures that the right version of the library is always used with your program. Also, because static libraries become part of your program, you can use them just like functionality you’ve written for your own program. On the downside, because a copy of the library becomes part of every executable that uses it, this can cause a lot of wasted space. Static libraries also can not be upgraded easy -- to update the library, the entire executable needs to be replaced.

A dynamic library (also called a shared library) consists of routines that are loaded into your application at run time. When you compile a program that uses a dynamic library, the library does not become part of your executable -- it remains as a separate unit. On Windows, dynamic libraries typically have a .dll (dynamic link library) extension, whereas on Linux, dynamic libraries typically have a .so (shared object) extension. One advantage of dynamic libraries is that many programs can share one copy, which saves space. Perhaps a bigger advantage is that the dynamic library can be upgraded to a newer version without replacing all of the executables that use it.

Because dynamic libraries are not linked into your program, programs using dynamic libraries must explicitly load and interface with the dynamic library. This mechanism can be confusing, and makes interfacing with a dynamic library awkward. To make dynamic libraries easier to use, an import library can be used.

An import library is a library that automates the process of loading and using a dynamic library. On Windows, this is typically done via a small static library (.lib) of the same name as the dynamic library (.dll). The static library is linked into the program at compile time, and then the functionality of the dynamic library can effectively be used as if it were a static library. On Linux, the shared object (.so) file doubles as both a dynamic library and an import library. Most linkers can build an import library for a dynamic library when the dynamic library is created.

Installing and using libraries

Now that you know about the different kinds of libraries, let’s talk about how to actually use libraries in your program. Installing a library in C++ typically involves 4 steps:

1) Acquire the library. The best option is to download a precompiled package for your operating system (if it exists) so you do not have to compile the library yourself. If there is not one provided for your operating system, you will have to download a source-code-only package and compile it yourself (which is outside of the scope of this lesson). On Windows, libraries are typically distributed as .zip files. On Linux, libraries are typically distributed as packages (eg. .RPM). Your package manager may have some of the more popular libraries (eg. SDL) listed already for easy installation, so check there first.

2) Install the library. On Linux, this typically involves invoking the package manager and letting it do all the work. On Windows, this typically involves unzipping the library to a directory of your choice. We recommend keeping all your libraries in one location for easy access. For example, use a directory called C:\Libs, and put each library in it’s own subdirectory.

3) Make sure the compiler knows where to look for the header file(s) for the library. On Windows, typically this is the include subdirectory of the directory you installed the library files to (eg. if you installed your library to C:\libs\SDL-1.2.11, the header files are probably in C:\libs\SDL-1.2.11\include). On Linux, header files are typically installed to /usr/include, which should already be part of your include file search path. However, if the files are installed elsewhere, you will have to tell the compiler where to find them.

4) Tell the linker where to look for the library file(s). As with step 3, this typically involves adding a directory to the list of places the linker looks for libraries. On Windows, this is typically the /lib subdirectory of the directory you installed the library files to. On Linux, libraries are typically installed to /usr/lib, which should already be a part of your library search path.

Once the library is installed and the IDE knows where to look for it, the following 3 steps typically need to be performed for each project that wants to use the library:

5) If using static libraries or import libraries, tell the linker which library files to link.

6) #include the library’s header file(s) in your program. This tells the compiler about all of the functionality the library is offering so that your program will compile properly.

7) If using dynamic libraries, make sure the program knows where to find them. Under Linux, libraries are typically installed to /usr/lib, which is in the default search path after the paths in the LD_LIBRARY_PATH environment variable. On Windows, the default search path includes the directory the program is run from, directories set by calling SetDllDirectory(), the Windows, System, and System32 directories, and directories in the PATH environment variable. The easiest way to use a .dll is to copy the .dll to the location of the executable. Since you’ll typically distribute the .dll with your executable, it makes sense to keep them together anyway.

Steps 3-5 involve configuring your IDE -- fortunately, almost all IDEs work the same way when it comes to doing these things. Unfortunately, because each IDE has a different interface, the most difficult part of this process is simply locating where the proper place to perform each of these steps is. Consequently, in the next few lessons in this section, we’ll cover how to do all of these steps for both Visual Studio Express 2005 and Code::Blocks. If you are using another IDE, read both -- by the time you’re done, you should have enough information to do the same with your own IDE with a little searching.

A.2 -- Using libraries with Visual Studio
23.7 -- Random file I/O

85 comments to A.1 — Static and dynamic libraries

  • Alan

    Hi, I heard a lot about header-only libraries but since all of the libraries apparently are header only as in that they have no source code, only the precompiled .lib files, i'm kinda confused about those header-only libraries. Could you please tell me what they are?

    • They ship without binaries and without source files. The entire source code is written in the header file. This can make inclusion easier, but it can tremendously slow down compilation and cause errors.

  • Sid

    So basically libraries are things that contain header files which in turn contain some symbols which are defined in other files like the .lib and .dll files. All OK till here.

    What is the difference between Dynamic Libraries and Static Libraries? - Dynamic ones are taken into account during runtime.

    OK, but I have heard many many people say that static library files (.lib) are usually smaller in size than the dynamic counterparts. Why would that be so?

    And if the only difference is when they are linked then why can't they be used interchangeably?

    • Alex

      Libraries are precompiled source code that provide an interface. The .h provides an interface for the compiler to check types, and the library itself is linked in.

      Static libraries are compiled into the source executables, whereas Dynamic libraries are standalone and bound dynamically at runtime. I presume static library files would be smaller because they need less scaffolding for the dynamic linking, but that's just a guess. I don't know that the size difference is substantive. A single library can be provided in static or dynamic form from the same source, as to why they aren't identical, clearly they require different packaging to function.

  • When it comes to .dll in Windows and .so on Linux, I can say I've seen .so a lot on Mac when it handles dependencies for console programs. When it comes to desktop applications, which are on Mac bundled in a folder with the ".app" extension, the dynamic libraries are often bundled as well in folders with the ".framework" extension in the "Framework" folder inside the bundle, and the files themselves bearing the ".dylib" extension. Depending on how commonly the library is used, these .dylib files or even the .framework folders are simply symlinks to files and folders stored in a special folder for that on Mac, but I must admit, as I used up until now mostly languages that didn't really care about that kind of stuff, I never fully sorted that out, and since Apple has gone to see their own customers as their worst enemies (well a tyrant fears the people he oppresses the most, and that is how Apple behaves now, IMHO), I am planning to switch back to Windows.

    I am also not sure if simply symlinking to dynamic libraries is always a good idea on Mac, due to the strict rules of the AppStore (but to be frank, I always avoid the AppStore whenever I can).

  • Trevor29

    "When you compile a program that uses a static library, all the functionality of the static library becomes part of your executable."
    This isn't necessarily so. The linker (which creates the final executable file from the various separately compiled files and libraries) will only include those modules from the static library that it needs to. For example, if you create a simple accounting program, the linker wouldn't normally include the trigonometry routines from the maths library (unless these were bundled with the logarithm and exponential functions which might be needed by an accounting program). Therefore it might be better to say:
    "When you compile and link a program that uses a static library, all of the required functionality from the static library becomes part of your executable."

  • Sepehr

    What is the benefit of using import library as opposed to dynamic library? I know it provides the means to treat the library as a static one, but are there other advantages in using import libraries?

    • Alex

      The lesson explains this:

      "One advantage of static libraries is that you only have to distribute the executable in order for users to run your program. Because the library becomes part of your program, this ensures that the right version of the library is always used with your program. Also, because static libraries become part of your program, you can use them just like functionality you've written for your own program."

      Is there something else you're curious about?

  • Shekhar

    hello friend

    I want to use libcurl ( in my project but I'm getting so many different type of error please help me out and guide me how to use it

  • Lim Che Ling

    Hi, I am sorry if my questions look stupid. Here they are:

    "3) Make sure the compiler knows where to look for the header file(s) for the library. "
    No matter the library is DYNAMIC or STATIC, we always need to do this step by "setting header search path", right?

    "4) Tell the linker where to look for the library file(s)."
    On this point, you are referring to the case when using DYNAMIC library only? So the actions of "setting library search path" or "link binary with libraries" is in fact telling linker where to look for dynamic library, is this correct?

    "5) If using static libraries or import libraries, tell the linker which library files to link."
    Apparently this is talking about static lib/import lib. So the action is "setting other linker flag"? Or "setting some kind of paths?" I do not what is the actual action we have to take "to tell the linker which library to link".

    "6) #include the library’s header file(s) in your program."
    So this also applies to both DYNAMIC and STATIC lib right?

    I just want to put in perspective when using opencv. I installed opencv using Homebrew. I set "header search path" (point 3), I set "library search path" (point 4), then I set "Other linker flags". When I set other linker flags, do I use static library and "tell the linker which library files to link"?

    Thanks for clarifying

    • Alex

      3) Yes.
      4) No, this is for both static and dynamic libraries. This is just an additional path to tell the IDE where to look for library files.
      5) This is for both static and dynamic libraries. Either way the linker needs to validate that all of the objects being used are actually defined.
      6) Yes, this is needed to satisfy the compiler.

      In some IDEs (e.g. Visual Studio), step 4 and 5 are combined into a single "reference the library file you want to use" step.

  • Sander

    Hey do you know how to make an reflective dll instead of a normal dll?

  • George Collins

    Thanks for the article. I am looking for a C++ library which can convert PDF into text, and have found Xpdf: . I have downloaded the tool kit that it offers, in which there are a couple of folders (bin32 and bin64) that contain executables, a 'doc' folder, and some instruction text files. I can not see a header file though. Could anyone advice me on how to link this to my xCode project?

  • Mr C++

    If there is any upgradation done in the library, then only the code in the standard library would have to be recompiled(which means all the executables wouldn't have to replaced), No? All the programs including the header files wouldn't have to recompiled, no?  
    And, static & dynamic libraries are linked(not compiled) into the program, yes?
    Waiting for your reply....
    Thanks in Advance :)

    • Alex

      Static library ARE compiled into the program. Dynamic libraries are not.

      Therefore, if the library is compiled into your application statically, then yes, you'd have to relink your program and replace the executable in order to update the library. If the library is dynamically linked, then no, you wouldn't have to relink, you'd just replace the library with the updated version.

      • Mr C++

        Ok, so when we made are own header file with the function declarations and all the function body in a cpp file, you said that only the main program needs to upgraded if any upgradation is required, so that was an example of dynamic library ?
        Thanks :)

        • Alex

          No. Dynamic libraries are separate files -- .dll files on Windows, and .so files on Unix.

          • Mr C++

            Sorry ! What I Meant To say Is Do They Also function like dynamic libraries ( only function ) ( as in their case also, only the main file needs to be upgraded ) ?

            • Alex

              No. Dynamic libraries can be replaced without any compiling. Normal programs still need to be recompiled when changes are made -- just if you organize them well, you can minimize the amount of recompilation needed.

      • Trevor29

        Strictly speaking, your program files do NOT need to be recompiled, as they haven't changed (unless the library header files have a breaking change). What is required is that your compiled files need to be relinked to the updated library files to generate a new executable file.

  • Sivaprakas

    Hi Can i use the .so inside my java web Service? if it is possible can you share some links of tutorial?

    • Alex

      Seems like it:

      • Sivaprakas

        Hi Alex actually need to develop OCR application on Linux but the OCR SDK only support c++ language on Linux , c++ we can't call from outside web service right so i need to develop 2 application

        1 for communication
        1 for OCR

        java web service for communication
        c++ executable for OCR process

        java web service get the file bytes from outside web services and write it local path then pass the path of the file to executable and the executable do ocr process and return the status of the ocr, java web service receive the status if job done read bytes of the ocr file and send as response to the outside web service. is my approach is good or bad? any suggestion?

        For the previous question i want to consume the c++ Shared Library ( .SO ) in java web service

        • Alex

          I don't think you need the java web service. There are 3rd party libraries that allow you to create RESTful services directly in C++. See

  • C++ Learner

    thank you very much for this great tutorial, this website is always in my bookmark's bar :)

  • Himans

    Hey alex. From which site i should start studying c? Any suggestions?

  • Matt

    In your second to last paragraph, you forgot "is":
    "The easiest way to use a .dll to copy the .dll to the location of the executable."

  • Hi Alex,
    Thanks for sharing your insights. It's of great help.
    I spotted two supposed mistakes: "... to look for the library file(s) for the library" and "... each project that wants to uses ...".
    Feel free to remove this comment after fixing them.

    P.S. While I think it's pretty cool that you integrated Gravatar into your WordPress, it was a surprise to see my picture posted publicly. "Email (will not be published) (required)" gave me the impression that one could comment anonymously. Personally I don't mind, but you might want to give either a warning or a choice there.

    • Alex

      Thanks, fixed.

      WordPress comes with built-in Gravatar integration. There might be a way to remove it, but most users seem to like it.

      For future reference, you can make up an email address if you don't want your Gravatar to show.

  • Ola Sh

    Thanks for your response. Does interface refer to the header file since the interface contains the function declarations, or are they different? If they mean the same thing, wouldn't the executable contain duplicate code. Thanks for clarifying.

    • Alex

      Remember that libraries are linked in, not compiled. So all libraries should come with header files containing the relevant declarations, so the compiler will be satisfied that you know what you're doing.

      Libraries have their own interfaces, which are essentially the functions the library has available to be called by your program. Libraries may also have internal functions that are not made available as part of the interface, much like a class can have private member functions. For static libraries, you can call these external functions directly, since they're compiled into your program. For dynamic libraries, calling these functions is more complicated (they can't be called directly, you have to get a function pointer to them and then invoke them through the function pointer). Using an import library provides a "bridge" to a dynamic library, so you can use the dynamic library as if it were a static library.

  • Ola Sh

    Hey Alex,

    Thanks for the good tutorial. Does the import library contain all the functionality of the dynamic library or does it only contain the functionality being used by a program's instance? If it contains all the functionality of the dynamic library, how then does it differ from traditional static libraries? Thanks for your help.

    • Alex

      An import library typically contains declarations for all of the functionality in the dynamic library. With a static library, both the interface and code to implement that interface get linked into your executable, bloating your executable. With an interface library, only the interface gets linked into your executable, the code that implements that interface stays in the dynamic library, which gets loaded dynamically and can be shared.

      So the import library really just provides a convenient way to use a dynamic library.

  • Lewis

    Hi, firstly I'd like to thank you for this website! It's the best resource I've seen for learning programming, and I'm very grateful for its existence!

    Anyway, I've made a program that uses OpenGL, Glew, and Glfw, that I would like to use on a non-dev PC, with a static exe (containing all necessary dlls etc) and I think I'm getting conflicting runtime linking. How can I make sure all of the third party (or not) libraries I'm using are compiled in the same way? I hear this online: "make sure all dependencies use the SAME runtime" and they leave it at that. Do you know how I can check this and get them all to 'run the same way'?

    Glfw3.lib is apparently already static, I've defined Glew to be static in the source code, I've set the release build runtime to Multithreaded /MT, but I'm getting 6 unresolved externals with basic c functions and a warning that "MSVCRT conflicts with use of other libs".

    Sorry for the huge question, but thanks again for this resource :)

  • Matt

    Found some typos:
    * "mechanisms" should be singular: "This mechanisms can be confusing..."
    * "know" should be plural: "...make sure the program know where to find them."

  • Erica G.

    Great Article. Thanks for the info. Does anyone know where I can find a blank IDES work form to fill out?

  • n shah

    Very nice, clearly explained and informative article.. Thanks for posting!

  • george

    So static and dynamic libraries differ in the way they are linked to the program, right? Are there differences in the structure of a static and a dynamic library, that identify their type? If not, then one and the same library can be used as either a static or a dynamic based on the linker options, true?

  • Nehme

    Thank you !
    Is there any difference, in performance side, between dynamic and static libraries ?

  • maen

    It's really very nice, simple and valuable article
    Thank you so much

  • heya

    7) If using dynamic libraries, make sure the program know where to find them.

    should be "knows" instead of "know"

  • Kartikay Malhotra

    Simply wonderful! Your articles are very nice to read. The reason is simple - no part is introduced out of place.

    Congratulations, on your accomplishment.

  • zeus

    very informative! thank you! bookmarking this for future reference, I learned a lot from this and can definitely come in handy later on. Thanks again!

  • Ivan Frohne


    You know, it's annoying to have your sparkling prose spoiled by the word "don't" spelled out as "don" followed by the three special characters circumflex a, the Euro sign, the trademark (TM) superscript, finally followed by "t". I see this sort of flub in web newspaper pieces all the time too. Has HTML failed us here? Or what.

    --Ivan Frohne

    • That's been happening to a lot of my articles. It appears to be some sort of strange wordpress database corruption. I'm not sure what causes it. In any case, I fixed up this instance by hand.

      • I've seen this type of behavior when copy & pasting from Word to an HTML editor or text field in a browser.

        Do you write in word first?

        • Nope. I tend to write directly in WordPress, as it autosaves for me. When I've seen this happen, it's happened to multiple articles simultaneously. I'm hoping the upgrade to WordPress 2.7 fixes whatever makes it happen.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]