What is the need for a library in C++?

Viewed 88

Header files contain only the declaration of the function and the actual implementation of the function is in the library. If they don't want to share source code they can share the obj file. Why do we use a Library when the implementation of a function can also be done in another C++ file?

3 Answers

Usually, a library is a collection of several translation units. A library archive is simply a convenient way to bundle the separate object files into one blob.

Besides that, shared libraries add the ability of dynamic loading and sharing of commonly used libraries between multiple dependents which isn't possible with a plain object file.

Libraries used in general as a collection of functions implements by other developers and can used by another developers " as a general used" , also provide a benefit to minimize your code and also u can take a function from library and edit the implementation as u need.

As other people explained I want to add more into it, Library provides you Reusability across multiple systems regardless of in which language they are written in Different Language unless it follows the same ABI. For example, A library written in C can be easily used with Rust, by wrapping the same function in Rust syntax.

For example, a function in C has this signature.

int return_num(int a);

If we write it in Rust, which will interact the same way as C do.

extern "C" {
    fn return_num(x: i32) -> i32;
}
Related