In Coding #101 we got acquainted with C++, the principal programming language in which Bitcoin Core is written. Today we will go through some of the key components of every C++ projects.
Header files
A header file is a type of file that stores predefined functions; it allows the programmer to re-use the same functionalities in different parts of the program, thus reducing the complexity and the size of the project.
In C++, header files commonly present a .h extension (or .hpp). In order to add them in a project, the preprocessor directive1 #include
must be used. When a header file is included in a project, all the functionalities (functions, classes, structures) that were decleared in it become available to the programmer.
There are two different kinds of header file:
Standard library header files: These headers are files that are already present in the C++ compiler and contain functions belonging to the standard library.
#include <iostream>
User-defined header files: These are user-defined files that contain previously written code:
#include <base58.h> // Example taken from Bitcoin Core
Source files
While header files contain the definitions of the different functionalities, source files contain their implementation, which means the actual source code.
We can easily identify a C++ source file from its .cpp extension.
An example from Bitcoin code
To better understand how the two type of files go together, let’s take a look at an example directly from Bitcoin code (I am not going to explain the code yet)
In the base58.h file, it is possible to find the definition of a certain function, DecodeBase58
:
bool DecodeBase58(const std::string& str,
std::vector<unsigned char>& vchRet,
int max_ret_len);
At the moment, there is still no information about how this function is implemented; it is possible to find it out by looking at the source file, base58.cpp:
// Include the corresponding header file first
#include <base58.h>
// Implement DecodeBase58 function
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet, int max_ret_len)
{
if (!ContainsNoNUL(str)) {
return false;
}
return DecodeBase58(str.c_str(), vchRet, max_ret_len);
}
Enough for today!
Thank you again for your attention, hope you enjoyed this brief lesson. If you have any feedback leave a comment!
Brief but one step closer!