when we use c++ , we always need write many library code so that we can use it in many places. in the article, i will introduce how to write and use dynamic library in windows and linux.
1 . First i will introduce dll technique in the windows platform.
A. it is very easy to write a dll file. first build a dll project in the vs2008 and write code like this:
extern "C" __declspec(dllexport) int max(int a , int b);
compile the project and we can find .dll and .lib file in the debug directory.
B. next step is using dll in our project.
build another test project. create a new and in the file write code like this:
extern "C" __declspec(dllimport) int max(int a, int b);
if we use vs2008 then we should add .lib file the project property or we can use the instruction as following:
#pragma comment(lib,"libname.lib");
and that's all we should do . it is very easy as i said above.
2. now i wll introduce how to use lib in the linux platform
dll is only available in the windows platform, so we can not write a dll project in the linux.
But we can use lib in the linux. it is very easy to write a lib in the linux. much easier than in the windows.
in the lib project functions are not required to add __declspec(dllexport)
But in the makefile we should indicate that the output file is a library object.
$(CC) -shared -Wl,-soname,lib$(name).so.$(majorVersion) $(LDFLAGS) -o $@ $^
the sentence above means the output file a shared library object and name is lib$(name).so.$(majorVersion)
when we want to use this library object file in the other linux project, we can write the following sentence in the makfile
$(CC) -o $@ $^ $(LDFLAGS) -lTcpServer2 -L $(libdir)/build/linux
-lTcpServer2 means we can to link dynamic library named as TcpServer2, the file name maybe libTcpServer2.so and searching directory is in the $(libdir)/buidl/linxu
we don't do anything else.everything is done.