Libraries vs classes in c++ - c++

I came across a terminology in C++ which is a library. The book I am reading states that iostream is a library , and it is a system library. Then After that it says in the book, "later, you will create your own library with the extension .h". Is a library the same as class because clearly, when I included my .h library, I actually had created a class.
If a library is the same as a class, what can we say about in C language , is it a class ?
Thank you.

Please note that this is just a simplistic explanation so you can wrap your head around it, not a pedantic or an exact and complete definition of a library.
A library is a collection of functions, classes and other stuff packaged together.
For instance the C++ standard library is (conceptually) composed of many libraries, e.g.:
string library
algorithm library
input/output library
etc.
The IO library contains some classes like:
std::iostream (actually a typedef to std::basic_iostream)
std::ios
std::istream
std::ostream
etc.
In order to use a library you basically need two things: the library headers in order to have access to the declarations and a library which needs to be linked to your project in order to have access to the symbols exported by such library. The OS comes with the C++ Standard Library preinstalled and the compiler -- when in C++ mode -- automatically links to it, so all you have to do is include the necessary headers.
In order to understand what a header is and what's it's role you first need to understand the difference between declaration and definition. You can reefer to What is the difference between a definition and a declaration? or any other reading material.
Then you need to understand the concept of compilation units. You can read What is a “translation unit” in C++ or How is compilation unit defined in c++.
Using all the above you should to be able to compile multiple source files into one executable and understand the basics mechanism involved. You can read Using multiple .cpp files in c++ program or How to use multiple source files to create a single object file with gcc
From here there is a small step to be able to create and use your own static library. You can start here: How to create a static library with g++?
Another important concept to understand is compilation/linking: How does the compilation/linking process work?
...or alternatively all you need to know is that in order to use std::iostream you need to include <iostream>. Ultimately it's up to you how much you want to absorb as "because that's how it's done" and how much you want to understand. Progress can be made only if you chose one of the options (spoiler: it's the latter).

Related

Is really required to separate c++ constructions in a .h and a .cpp files?

Well, I'm getting in C++ universe and this doubt came over.
It's too boring to have 2 files for each meaning-unit I choose to include in my program.
I know I can have multiple classes in the same (pair of) archive(s), however I would like to clarify if really there's no way to write just one file, instead of a .h and a .cpp ones.
I found some other answers (like this, that and that other) there are actually pretty explicative, but a quite older too. So hopping the language have got some improvement I came to ask:
Is there some compilation option, any another alternative extension, or whatever, that allows me to write just one file?
I appreciate it!
Okay, you need to understand what is going on. This isn't Java.
The .h file is the definition of your class. It's just an include file that can be used other places so those other places understand your class. Now, you CAN actually do the constructor inline, like this:
public:
Foo() { ... your code here ... }
This is perfectly legal. But the problem with this is simple. Everywhere you hit this constructor, the compiler has to insert that code inline. This leads to lots of the same code everywhere you create a new Foo.
If you put the code in your .cpp file, and then compile it, you get a .o file. That .o file includes a single copy of your constructor, and that's what gets called everywhere you create a Foo.
So separating the definition from the code results in smaller programs. That's less important nowadays than it used to be.
This is the nature of C++, and you should accept it.
The .h is an include file, used in other places. The .cpp is the implementation. It's not really onerous, once you grow accustomed.
You have to understand that C++ is a compiled language. When you compile a library, for example, the library contains machine-specific code. If you want to write a program that uses that library, your program has to be able to see function and class definitions to properly link that library. On the other hand, it is absolutely possible to write your entire program in header files -- indeed, the term header-only library exists to describe libraries that have no pre-compiled machine code. That means the responsibility of compiling it falls to you. You'll likely have longer compile times, and because of this, very large libraries are almost exclusively pre-compiled into binaries that are platform-specific (in the absence of a set of binaries for you machine, you must compile from source and link against the result). In theory, one could rewrite the C++ spec in such a way that only one file was necessary, but then those files would need to be present within any project that incorporates that library. For very large libraries, this can be a pain -- why include the full source of some engine when you could include just the definitions necessary to link into the binaries? This provides the added advantage of obfuscating the algorithms and implementation details from the client program. C++ is not an interpreted programming language -- it's important to think about it from the compiler's perspective.

The effect of number of functions in a C++ library

Suppose now two C++ libraries are available: one library has all the functions that will be needed by the program ( a C++ application program that will invoke the library), and the other one not only has the necessary functions that will be needed by the program but also has other functions that will not not used by the program. We assume that for the common functions in both libraries they are implemented in the same manner. My question is: when the program uses the library to perform a certain task, what's the effect of the library on the performance of the program?
The reason why I asked this question is because when developing a c++ library I often wrote some additional functions, which may not be invoked by the users of the library but are important for debugging. When the library is finished, I have two choices: one is to keep these auxiliary functions and the other is removing them or using other strategies of keep them (for example, define MACRO to disable these functions). If keeping these auxiliaries functions will not deteriorate the performance, I would like to keep them.
Everything else being the same, there will be no performance difference.
In addition, if the library is a static library, the linker will not include the functions that are not used, and the executables will have the same size.
Well if you have written a static library that I guess you have. Then the only difference it will create is that the static library functionality will be part of you executable no matter if you use it or not.
I don't think it will hurt you in terms of speed but yes it will occupy a lot more space since a copy of lib will be created with you executable.

Are Preprocessor Definitions compiled into a library?

Are they (preprocessor definitions) compiled into a static/dynamic library? For example, the FBX SDK needs KFBX_DLLINFO. A library that makes use of FBX SDK must include that. Now the client application, as far as I can tell from my limited experimentation, does not need to declare the definition again.
Now I can't think of a more practical scenario, but what if the client application 'needs' the definition to excluded (for example _CRT_SECURE_NO_WARNINGS compiled with a library, but what if I need those warnings?
In short: no.
In long:
For the most part, you can think of preprocessor definitions as a textual substitution mechanism. They are processed before compilation occurs (pre-compilation), so they transform the source code just before the compiler translates it to machine code, intermediate files, or whatever its target is. By the time you have a binary lib/obj/dll/exe/so file, the preprocessor definitions are long gone.
If you include a header in your code that was packaged as part of the library (e.g. in order to reference methods, types, enums, etc. defined by the library), then you are including preprocessor definitions that the library defines in that header.
In your case, if you include an FBX header, you might also be pulling in the preprocessor definition of KFBX_DLLINFO. The FBX binary library you're linking against was almost certainly built with that same header, so you are building against the same definition. This is a common pattern with libraries written in C/C++: common, shared header files along with a static or dynamic lib to build against.
Preprocessor definitions only exist during the compilation. They don't exist anymore in the compiled binary, be it static or dynamic library, or executable.
As Chris explains, #defines are a textual substitution mechanism. The expansion was traditionally performed as a pre-compilation step, with the main C++-language compiler not having (or wanting) access to the pre-substitution text. For this reason, #defines can do things that aren't possible with the language-based constraints of C++, such as concatenate values to form new identifiers. These days, compilers tend to embed the macro processing functionality, and may include some information about pre-processor symbols in the debugging symbol tables compiled into executables. It's not very desirable or practical to access this debug information for some client usage, as debug formats and content can change between compiler versions, aren't very portable, may not be terribly well debugged :-/, and accessing them may be slow and clumsy.
If I understand you correctly, you're wondering whether #defines from some lower-level library that your library is using will be automatically available to an "application" programmer using your library. No, they won't. You need to either provide your own definitions for those values that your library's API exposes to the application programmer (mapping to the lower-level library values internally if they differ), or ship the lower-level library header as well.
For an example of remapping:
Your library.h:
#ifndef INCLUDED_MY_LIBRARY_H
#define INCLUDED_MY_LIBRARY_H
enum Time_Out
{
Sensible,
None
};
void do_stuff(Time_Out time_out);
#endif
Your library.c:
#include "my_library.h"
#include "lower_level_library.h"
void do_stuff(Time_Out time_out)
{
Lower_Level_Lib::do_stuff(time_out == Sensible ? Lower_Level_Lib::Short_Timeout,
: Lower_Level_Lib::No_Timeout);
LOWER_LEVEL_LIB_MACRO("whatever");
}
As illustrated, usage of the Lower_Level_Lib hasn't been exposed in my_library.h, so the app programmer doesn't need to know about or include lower_level_library.h. If you find you need/want to put lower_level_library.h into my_library.h in order to use its types, constant, variables, or functions therein, then you will need to provide the app programmer with that library header too.

What's the difference between a header file and a library?

One of the things I'm having a hard time understanding is how the compiler works. I'm having a lot of difficulties with it, but in particular I keep getting headers and libraries mixed up. If somebody could clear things up a bit, that'd be great.
Think of both like this (Disclaimer: this is a really high-level analogy ;) ..
The header is a phone number you can call, while...
...the library is the actual person you can reach there!
It's the fundamental difference between "interface" and "implementation"; the interface (header) tells you how to call some functionality (without knowing how it works), while the implementation (library) is the actual functionality.
Note: The concept is so fundamental, because it allows you flexibility: you can have the same header for different libraries (i.e. the functionality is exactly called in the same way), and each library may implement the functionality in a different way. By keeping the same interface, you can replace the libraries without changing your code.
And: you can change the implementation of the library without breaking the calling code!
A header file is generally used to define an interface or set of interfaces within an application. Think of a header file as something which shows the external functionality of a program while omitting the technical implementation details.
For example, if you were optimising a program, you would most likely modify the source (.cpp) file to improve the algorithm, but the header file wouldn't change, because external clients still call the methods using the same set of parameters and return values.
In an object-oriented language like C++, a header file generally includes the following:
Class description and inheritance hierarchy
Class data members and types
Class methods
While there is nothing stopping code from being implemented in a header file, this is generally not favoured as it can introduce extra coupling and dependencies in the code.
In some cases (e.g. templated classes) the implementation must be defined in the header file for technical reasons.
A library is a collection of code which you want to make available to a program or group of programs. It includes the implementation of a particular interface or set of interfaces.
Code is defined in a library to prevent code duplication and encourage re-use. A library can be statically-linked (.lib) or dynamically-linked (.dll):
A statically-linked library defines a set of export symbols (which can be thought of as method definitions) which are then linked into the final executable (.exe) during the linking stage of the build process. It has the advantage of faster execution time (as the library doesn't need to be dynamically loaded), at the expense of a larger binary (because the methods are essentially replicated in the executable file).
A dynamically-linked library is linked during the execution of a program, rather than the linking of a program. It is useful when multiple programs need to re-use the same methods, and is used extensively in technologies such as COM.
One thing that may be confusing you is that the word library can have several meanings in C++. One meaning has been well-discussed here:
A linkable set of functions in a binary file. These can be statically linked or dynamically linked.
But there is another type of library: so-called header-only libraries (including parts of STL, TR1 and Boost). These do not exist in a separate binary form so the word library does not refer to a particular binary file but rather to a set of included header files.
Hope this helps.
Header only contains the declaration, whereas libraries also contains the implementaion.
A library is code, compiled into a set of object files. The object files contain the compiled machine code and the data declarations used by the code.
A header file defines the interface to a library: it tells you how to use the library correctly. In C/C++, a header file gives you a list of function names and how to call those functions: the number and types of parameters they take, the return type, the calling convention, etc. Header files have a lot of other stuff in them, too, but in the end, what it boils down is a set of rules for calling library code.
If Library in programming languages is a general library , then many books present in the library can be compared with functions/methods in languages . And also header files can be compared with the row number of the book
Suppose there is a book in some library in Hyderabad and in that library , that book is present in row Number 24 ...
The same way the address of the library is given by using the namespace std (for standard library) and row No is given by header file where all the books(methods in this case) of same time(all methods related to input/output streams) are put up
Header is typically used to contain the prototypes. Headers expand at pre-processing time so that at compile time, the code may have access to relevant function declarations/ prototypes.
Library is the actual software that contains the definitions of the function prototypes (present in the header). Library is used at link time. The definitions (present in library) are resolved at link time.
A header file describes how to call the functionality, a library contains the compiled code that implements this functionality.
HEADER FILE is that in which declaration of a function is written.By using header file we can access a particular function
while
LIBRARY FILE is that in which definition of a particular function is written.
MATH.H is a HEADER FILE while MATH.LIB is library file.
Working of HEADER File and LIBRARY in a Program.
A header file contains the links to libraries(libraries contain standard functions and methods), a compiler recognizes the standard functions used in the source code via a preprocessor, that resolves all the directives(directives are the lines in program preceded by # sign that include ) before the actual compilation of the program.
Thanks for reading!
I think library as a package of code which is reused many times and and that code is precompiled , hence it is available in standard form so that we do not have to write that code for every program that we develop .
And header file contain the reference to that code in simple way the functions we use in our program like "cin" and "cout" are fully defined in a standard library ,and header files like iostream header file contains the reference to that code.
So when we compile our code it we just get the precompiled for cin and cout, and we do not have to write the code for cin and cout for every time we use it.
Or In a more simple way we can say that a library contain codes for all the functions and a header file is way to reach that code.
A library is a collection of similar objects for occasional use . It usually contains programmes in object or source code form, templates, etc.
A header file is the location (interface) of the library
To paraphrase a classical joke, the difference is that the library has a header file while the header file doesn't have a library.
Libraries are like dead mummies,wrapped in white long threads. They are dead. Only way to release them is through header files. Header files contain ways to bring them to life and they can be brought to life many times(code reuse).
You can consider this example to understand- Math.h is a header file which includes the prototype for function calls like sqrt(), pow() etc, whereas libm.lib, libmmd.lib, libmmd.dll are some of the math libraries. In simple terms a header file is like a visiting card and libraries are like a real person, so we use visiting card(Header file) to reach to the actual person(Library).
Code from libraries will only be stored as needed for a header file. The whole header file will be stored, which saves processor storage area.

How to document the functionality in C++20 modules?

When providing a library to others, documentation of e.g. class member functions can be included in the header files which contain the declarations. If properly formatted, this documentation can also be interpreted and displayed by IDEs.
Using C++ modules, how can I pass on information about the functionality in the module without falling back to external documentation, e.g. Doxygen? I assume comments do not make it as such into the compiled interface file?
You are right, this question is actually pointless. I thought that - unless provided with the complete source code - libraries would be provided completely in binary format when using modules. Although the idea of deploying just one library file without additional files has its charme.