从静态链接库导出类的问题 [英] The problem about the class exported from static link library

查看:122
本文介绍了从静态链接库导出类的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我准备了一个非常简单的静态链接库项目(projectlib.lib),只包含lib.h和lib.cpp,我想导出一个名为c_lib1的类,我尝试了两种方法:

(1)在lib.h中声明类c_lib1并在lib.cpp中定义c_lib1。

(2)直接在lib.h中定义类c_lib1:

< pre lang =c ++> class c_lib1
{
public
int m_a,m_b;
int m_add( int a, int b)
{
return a + b;
};
};



然后生成projectlib.lib。接下来在一个应用程序项目(.exe)中,我使用这个静态库projectlib.lib,在应用程序项目中,使用上面的(1)方法,不能识别类c_lib1,但是使用(2)方法可以编译通过,这就是为什么?



我尝试了什么:



我有尝试了这两种方式

解决方案

不完全清楚,但我可以说......

所有声明必须在标题中(.h)文件,而实际的主体也可以在标题(.h)或源(.cpp)文件中...

微软有一个很好的演练:演练:创建和使用静态库(C ++) [ ^ ]


使用方法(1)时,这是静态库的常用方法,您必须在代码t中包含lib.h文件帽子使用你的图书馆。并且您必须告诉链接器包含lib.obj文件(请参阅链接器选项卡下的项目设置或相应的链接器命令行参数)。



使用方法( 2)编译器可以内联 m_app 方法的整个代码,因此调用代码不需要lib.obj文件来解析该引用。这就是你的例子工作的原因,尽管你可能没有将lib.obj指定给链接器。



但是:根据函数的大小,编译器不会必须内联函数,然后在链接时需要.obj文件。


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:

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

解决方案

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++)[^]


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.


这篇关于从静态链接库导出类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆