When learning C++ in school we never really talked about how to build libraries, so sorry for my rudimentary understanding.
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.
For example when I #include <cmath> I can now call sin(x) without having access to the cmath code to compile it. My question is if this works with classes that have data in them.
So can I create a library
//AccumulatorLibrary.h
class Accumulator
{
public:
int num;
int increment() {num++};
void otherFunctions(); //otherFunctions defined in the .lib file
}
And then call it
//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;
}
and get an output of 1 8 2 ?
In summary, if I figure out how to put a bunch of classes into a library file can I access any data I want to, as long as that data has an access function in the .h file?
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, and you don’t have access to the code in the .lib file?
Correct.
It does. A lot of C++ libraries expose classes and have their code precompiled in a library.
Wait, wait. .h files still contain C++ code (declarations and sometimes even inline implementations). .lib files are dynamically linked libraries. They’re the result of the compilation (and linkage) of the C++ source files.
You do have access to it: open it using a disassembler. It just won’t be C++ anymore.