Shared Utilities
To wrap up this section, let’s consider how we can share some of our code across different projects. In the forward declaration section we looked at how to share functions and procedures by using header files. So let’s create our own utilities.h header inside which we can put functions and procedures we want to share.
What can we share with other projects?
If we look back over the code we have created so far, we often have functions to read data from the user. This includes read_string
and read_integer
, and we could extend of this as we go.
To build this we first need to create two files:
- utilities.h - this will contain the function signatures. These are the promises that these functions will exist and can be used.
- utilities.cpp - this will contain the implementation of the functions.
This will mean that we have to compile both the utilities.cpp and the project code file. The following shows the command to run at the terminal to compile program.cpp and utilities.cpp into a single program called test. The important thing is that you are passing both files to the compiler, otherwise you will get a linker error when it tries to find anything implemented in the missing file.
Creating the header file
The header file will include header guards and the signatures for your functions. You can copy these from an existing project where you have declared these functions. Remember the signature is just the first line of the function declaration, terminated with a ;
where the block of instructions would go.
This header says that there are two functions available: read_string
and read_integer
. We have included the string header and added using std::string;
as we want to make use of the string type (which is not available without this).
Including the documentation in the header is a great idea, as this can then be read by the editors like VS Code and help describe the function as you go to use it.
Implementing the utilities
The code in the utilities.cpp will have just the code to implement these functions, but can include additional headers to access functions you need to implement these.
Using the utilities
Once you have this setup, you can now use these functions by including your header and compiling the utilities.cpp along with your other program code.
You can then compile and run this from the command line using:
Adjusting VS Code settings
To build and run this in VS Code, and to use the debugger, we will need to adjust the tasks.json to also compile the utilities.cpp
file along with the currently selected file. You can do this by adding a line to the args
settings as shown below. This list contains the arguments that are passed to the clang++
program when it is called, so including "utilities.cpp",
will add that file when the compiler is called.
You should be able to check the output tab when you build and run, and it will show you what VS Code called when it compiled your program.