Compiling to Wasm a project from several C++ sources
We compile a set of C++ sources into a single wasm file executable locally with wasmer.
In the previous article, we saw how to compile a simple C++ file into Wasm, which can then be run like any local program. But what if the project is made up of several source files?
1) Example of source to include in a project
The example is a small library of arithmetic calculations that could be included in various projects. These functions are intentionally simplistic so that we focus on the compilation method and not on the content.
/* Library of functions */
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
int mul(int x, int y) {
return x * y;
}
int fibonacci(int n) {
if(n < 2) {
return 1;
}
else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Save the program under the name demolib.cpp
White also a header file:
int add(int, int);
int mul(int, int);
int fibonacci(int);
The header file will be saved under the name demolib.hpp in the same directory as the main source.
2) Main source code
Source code of the demonstration containing the main function, and which uses the functions of the library.
/* Main file */
#include <iostream>
#include "demolib.hpp"
int main() {
int a = add(10, 20);
std::cout << "10 + 20 = " << a << std::endl;
int m = mul(10, 20);
std::cout << "10 x 20 = " << m << std::endl;
std::cout << "Fibonacci(16):" << fibonacci(16) << std::endl;
}
3) Compile to wasm
This time the compile command contains a list of several files to compile.
emcc demolib.cpp demo.cpp -o demo.wasm
This produces the following file:
demo.wasm
Run the program with the following command:
wasmer hello.wasm
Which will display:
10 + 20 = 30
10 x 20 = 200
Fibonacci(16):1597