If I create a static library in C++ in Linux such that a ".a" file is produced, how do I (or anyone else) use the library? For example, my library defines a class. I assume that it is not sufficient merely to provide the ".a" file, but also to provide a header file. How do I know what header files must be provided with the ".a" file?
For example, do I need to provide all header files that were included anywhere in the code for my library?
You can have the libraries installed without the headers. You can't then compile code that uses the header, but you can run code that uses the shared library.
The primary purpose of a header file is to propagate declarations to code files. Header files allow us to put declarations in one location and then import them wherever we need them. This can save a lot of typing in multi-file programs.
If you have a lot of files, multiple copies of a static library means an increase in the executable file's size. If, however, the benefits of execution time outweigh the need to save space, the static library is the way to go.
Yes, because it's still based on C. You can answer your own question: Don't use them and try to compile without them. If you can't, then the compilers still require them.
Header files provide the "declarations" for the classes and functions. These are needed by the compiler, so it can a) validate that you are passing the right parameters, and/or setting the right data members of classes / structs, and b) so it can know how to call those functions.
void do_something(int a, std::string& s);
tells the compiler that this function is expecting two parameters: an int
, and a string&
. This validates that you are passing the right types of parameters (a language-level construct), and it explains what the object code in the compiled library is expecting (two arguments -- how is determined by calling convention.)
If that compiled library is using code from another library, you do not have to provide those headers, because they have nothing to do with code that you've written. The libraries are working at a "application binary interface" (ABI) level, not an "application programming interface" (API). That means they're just passing around pointers, etc. Not parameters with C types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With