How to Work With Libraries in C++
For someone who wanna bring c++ to real world, it’s a necessary to know how to use third parties library. In my case I wanna bring cryptography( as a sample of cpp libraries) to c++! I would talk about the cryptography itself in a separate post, and of course crypto++!
As a medium c++ programmer you definitely know how our codes are compiled and how they become an executable file.
[blockquote author=””]Lets have a brief explanation – our codes will at first compile into some object files ( by compiler) then they would link together into an executable file (by linker of course).[/blockquote]
What are libraries?
Not all of our linkers output are executable , they can be
- Dynamic library
- static library
Libraries are some file which are already written and compiled projects that you can use them in your program.
Differences between Dynamic and Static Cpp Libraries:
Static libraries would link to your executable file at build time, they would be inside of your executable file while dynamics don’t, they are called from out side your executable file, therefore they must be completely separate file from your executable.
In this article we are going to talk about static libraries and use them in our project;
Let’s do it:
- Make your IDE ( therefor your compiler) know where are the #include files;
- Introduce your library files;
- The name of your libraries;
Here I would use crypto++ library in our code and check out what would happen if we don’t do any of these steps;
- Our Code:
as you can see, compiler couldn’t find our include file:
Error C1083 Cannot open include file: 'osrng.h': No such file or directory Sample Library c:\users\user\documents\visual studio 2015\projects\sample library\source.cpp 2 Build
now we would do our first step:
Introduce the include files:
- Project -> Properties
- c/c++ -> general ->additional Include Directories ->edit:
- choose directory of library:
- select folder and press OK the dialog boxes.
After Including how your code reacts:
as you can see, intellisense doesn’t have any problem because she(!) found include files, the only(s!) problem is from linker:
Error LNK2001 unresolved external symbol "public: virtual unsigned char __thiscall CryptoPP::RandomNumberGenerator::GenerateByte(void)" (?GenerateByte@RandomNumberGenerator@CryptoPP@@UAEEXZ) Sample Library C:\Users\user\Documents\Visual Studio 2015\Projects\Sample Library\Source.obj 1 Build
2. Introduce library file;
- Project -> Properties
- linker -> general ->additional Library Directories ->edit:
- choose directory of library as same as include files;
- now u should give the linker a cheat, the name of library file:
- linker -> input -> addiional dependencies
- type the name of library. in my case : cryptopp.lib
now final build:
My one worked! didn’t yours? share in comment