For performance reasons, it can be useful to write functions in C/C++ which can then be called within Python. This will be an introductory post, in where we will call a simple C++ function (with a dependency) within Python using [SWIG](http://swig.org/).
First we need to install SWIG:
```bash
sudo apt install swig
```
We're going to use [GNU MP](https://gmplib.org/) in order to have arbitrary precision arithmetic for our factorial function.
```bash
sudo apt install libgmp-dev
```
## Source Setup
Normally people use headers for larger C++ programs, though we're going to create one just so we can see how to include it later in SWIG. Let's called this file `factorial.hpp`
```c++
#ifndef FACTORIAL_H
#define FACTORIAL_H
std::string fact(unsigned int n);
#endif
```
In order to get it the large number from C++ to Python. We are going to use `std::string` as the return of our `fact` function.
Here is the source `factorial.cpp`
```c++
#include <gmpxx.h>
#include "factorial.hpp"
std::string fact(unsigned int n) {
if (n == 0) {
n = 1;
}
mpz_class result(n);
while (n > 1) {
n--;
result *= n;
}
return result.get_str(10); // Base 10
}
```
Now that we have our C++ code, we need to create a swig template file called `factorial.i`
```
%module factorial
%{
#include "factorial.hpp"
%}
%include <std_string.i>
%include "factorial.hpp"
```
Since we're returning a `std::string` we need to tell SWIG what that is. We do this through the `<std_string.i>` include.
We can now ask SWIG to write the C++ code that will interface with Python. This will create the files `factorial_wrap.cxx` and `factorial.py`.
| -O2 | Perform nearly all supported optimizations that don't involve a space-speed tradeoff. |
| -fPIC | Create Position-Independent Code |
| -c | Don't link at this time |
To compile `factorial_wrap.cxx` we need to include the directory where `Python.h` lives. You can find this by issuing the command `locate Python.h`. Below is where it is located on my system.