Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a header file required for using a static library?

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?

like image 881
synaptik Avatar asked Dec 16 '12 07:12

synaptik


People also ask

Does static library need header files?

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.

Why header files are required?

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.

When should I use static library?

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.

Are header files required?

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.


1 Answers

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.

like image 72
Jonathon Reinhart Avatar answered Oct 04 '22 05:10

Jonathon Reinhart