Click here to Skip to main content
15,888,008 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have prepared a very simple static link library project(projectlib.lib),only include lib.h and lib.cpp,i want to export a class named c_lib1,there are 2 ways I tried:
(1) Declare class c_lib1 in lib.h and define c_lib1 in lib.cpp.
(2) Define class c_lib1 in lib.h directly:
C++
class c_lib1
{
   public:
     int m_a, m_b;
     int m_add(int a, int b)
          {
             return a + b;
          };
};

Then generate projectlib.lib. Next in an application project (.exe), I use this static library projectlib.lib,in the application project, use the above (1) method, can not identify class c_lib1, but the use of (2) method can compile through, this is why?

What I have tried:

I have tried both these two ways
Posted
Updated 26-Dec-16 0:02am
v2

Not exactly clear, but this I can say...
ALL the declaration must be in the header (.h) file, while the actual body can be in the header (.h) or the source (.cpp) file too...
There is a nice walkthrough from Microsoft here: Walkthrough: Creating and Using a Static Library (C++)[^]
 
Share this answer
 
When using method (1), which is the usual way for a static library, you must include the lib.h file in the code that uses your library. And you must tell the linker to include the lib.obj file (see your project settings under the linker tab or the respective linker command line arguments).

Using method (2) the compiler can inline the entire code of your m_app method and hence the calling code doesn't need the lib.obj file to resolve that reference. That is why your example is working although you probably did not specify the lib.obj to the linker.

BUT: Depending on the size of the function the compiler will not necessarily inline the function and then the .obj file will be needed at link time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900