在学校学习 C++ 时,我们从未真正讨论过如何构建库,很抱歉我的初步理解。
从我在网上阅读的内容来看,库似乎只是已经编译过的代码的集合,然后有一个 .h
。列出该库中可访问的函数的文件。
例如当我 #include <cmath>
我现在可以调用 sin(x)
无需访问 cmath 代码即可对其进行编译。我的问题是这是否适用于其中包含数据的类。
那么我可以创建一个库吗
//AccumulatorLibrary.h
class Accumulator
{
public:
int num;
int increment() {num++};
void otherFunctions(); //otherFunctions defined in the .lib file
}
然后调用它
//Main
#include "AccumulatorLibrary.h"
#include <stdio>
int main()
{
Accumulator A(0); //initalize num to 0
Accumulator B(7); //initalize num to 7
cout<<A.increment;
cout<<B.increment;
cout<<A.increment;
}
并得到 1 8 2
的输出?
总而言之,如果我弄清楚如何将一堆类放入库文件中,我就可以访问我想要的任何数据,只要该数据在 .h
中具有访问函数即可。文件?
或者更基本的问题,做一个.h
和 .lib
文件的工作方式与常规 C++ 代码完全相同,只是在使用时无需编译,并且您无权访问 .lib
中的代码。文件?
最佳答案
From what I've read online, it seems like a library is just a collection of code that is already compiled, and then there is a .h file that lists what functions are accessible in that library.
正确。
My question is if this works with classes that have data in them.
确实如此。许多 C++ 库公开类并将其代码预编译在库中。
Or a more basic question, do a .h and .lib file work exactly the same as regular c++ code except that it doesn't have to be compiled when you use it...
等等等等。 .h 文件仍然包含 C++ 代码(声明,有时甚至是内联实现)。 .lib 文件是动态链接库。它们是 C++ 源文件编译(和链接)的结果。
...and you don't have access to the code in the .lib file?
您确实可以访问它:使用反汇编程序打开它。它不再是 C++。
关于c++ - 带有类的库如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840553/