Creating C++ Projects with Multiple Files
Multiple Files??
Because C++ involves compiling and linking code into one program, it is actually quite simple to write multiple files for a project and access functions that are located in other files. This is done through declarations, a.k.a declaring in one file that a certain function exists in another file. Function definitions can only be written once, but there is no limit to function declarations. A function declaration is identitical to the first line of a function definition except that there’s a semicolon at the end.
int example_function(std::string s, int i);
Because the compiler reads top down, it is a good idea to declare functions exist before they are used in your code. Declaring functions before they are used in main is known as forward declaration.
However, it would be very tedious and messy to have forward declarations for every file that you write. Good news! It’s possible to put all of them into one file and access them using #include. These files are called header files that have the extension .hpp (or .hxx, .h, etc). While external libraries like iostream and vector are included using < >, internal files of the same project, like headers, are included using “ “.
include <iostream>
include "header.hpp"
Tips for Using Headers
When working on a particularly extensive project, include #pragma once
in the header file to prevnt it from being reiterated! Also, be sure to never #include
source files/.cpp files. Lastly, header files do not need to be compiled.
Documentation
C++ uses Doxygen for documentation which has its own specific syntax a little different from Docstrings in Python.
#include <vector>
/*! \brief Give a brief explanation of the function here.
*
* Here, write a longer, more detailed explanation
*
* \param [in] write down what the function takes in here
* \return write down what is returned by the function here
*/std::vector<double> example(const std::vector<double>);
As seen above, documentation goes before the function declaration rather than after, and starts with a /*! and ends with a */
In between, both brief and detailed descriptions of the function, parameters, and what is returned by the function is written here.
Testing Code in C++? Catch2
Catch2 is the way to go. Catch2 is a package that is used to test C++ code, similar to Pytest for Python.
Download using the link below:
https://raw.githubusercontent.com/catchorg/Catch2/v2.13.9/single_include/catch2/catch.hpp
To use Catch2, define #define CATCH_CONFIG_MAIN
at the top to automatically create a main
function.
With the function you want to test in the code, write out a test case.
TEST_CASE("Example")
{
REQUIRE(function(param) == expected_value;
}
Now, compile both the test file and the original C++ source file.
g++ test.cpp example.cpp -o test_example
./test_example