How to Create a Static Library in Visual C++

  We all come across static libraries while developing Windows programs. Usually, these files contain definitions of various functions which are declared in header files. For example, you may have seen glut32.lib (containing definitions of the functions declared in glut.h)

How to Create a Static Library in Visual C++

Static libraries are a good way to organise your program’s function declarations and function definitions. You can also create your own static libraries easily once you learn how to create a static library. This tutorial shows you the steps involved in creating a simple static library.

 

1. Create a new Win32 Console Application project in Visual C++.
Create a new Win32 Console Application project in Visual C++

2. Click Next.

Click Next
3. Select the radio button labelled Static Library, uncheck the Precompiled Header check box and click Finish.
Select the radio button labelled Static Library, uncheck the Precompiled Header check box and click finish
4. Add a .cpp file and a .h file.

5. Make declarations in the header file and definitions in the source file.

.cpp file
.h file

6. Build the project.

Build the Project
7. The static library (.lib file) is ready to use. Move it to “C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib” (I am using Visual Studio 2013, if you are using another version of Visual Studio, the ‘lib’ folder in your case may have a different location).
Please Note that the Program Files (x86) folder exists only on 64-bit versions of Windows. On 32-bit versions of Windows, you need to use the Program Files folder.
The static library (.lib file) is ready to use

8. Now, in order to use this static library in a program, create a new Win32 Console Application project in Visual C++.

Create a new Win32 Console Application project in Visual C++

9. Click Next.

Click Next

 Click Finish.

Click Finish

 

10. In the source file, include the header file of the static library you just created. Also, add #pragma comment(lib,”mystatic.lib”) before main(). Execute the program by pressing Ctrl + F5.
Execute the program by pressing Ctrl + F5

11. The resulting program window appears below.

The resulting program window
You can download the static library project displayed in this article here.
Tell us whether this article helped you in your comments below.
(Visited 571 times, 1 visits today)

One comment

  • Static libraries are a great way to ensure that your program would not have any trouble executing as a standalone program i.e. without any dependencies. On the other hand, DLLs make me crazy.

Leave a Reply

Your email address will not be published. Required fields are marked *