Generating a library for a Wasm project
C++ source files are compiled into object files combined into a single library file.
In the previous article, we saw how to compile in Wasm a project from several C++ sources to build a local program. To avoid recompiling all the source files each time one of them is modified, you must create a library of object files that can be included directly in a project.
For this to work, object files must not be produced by a classic compiler like GCC or even CLang, they must be generated by Emcc.
1) Library of two files
The sample library consists of two files, one contains simple arithmetic functions and the other contains the Fibonacci algorithm.
First source file:
int add(int x, int y) {
return x + y;
}
int mul(int x, int y) {
return x * y;
}
float divide(float x, float y) {
if(y == 0) return 0;
return x / y;
}
Second source file:
int fibonacci(int n) {
if(n < 2) {
return 1;
}
else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
The source codes are saved under the names of arithm.cpp and fibonacci.cpp
The header files will be saved under the name of arithm.hpp:
int add(int, int);
int mul(int, int);
float divide(float, float)
And fibonacci.hpp:
int fibonacci(int);
2) Main source code
Source code of the demo program using library functions:
/* Demonstration */
#include <iostream>
#include "arithm.hpp"
#include "fibonacci.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;
float d = divide(30, 10);
std::cout << "30 / 10 = " << d << std::endl;
std::cout << "Fibonacci(16):" << fibonacci(16) << std::endl;
}
3) Generating the library
First file:
em++ arithm.cpp -c -o arithm.o -Oz -s SIDE_MODULE=1 -s WASM=1
Second file:
em++ fibonacci.cpp -c -o fibonacci.o -Oz -s SIDE_MODULE=1 -s WASM=1
You can optionally include external header files in the command with the -I option
The object files are combined into a library file with the emar command included in emscriptem.
emar rcs demolib.a arithm.o fibonacci.o
This produces the following file:
demolib.a
4) Using the library
The library file can then be included in the compilation command of the main program.
emcc demolib.a demoprj.cpp -o demoprj.wasm -s WASM=1
5) Running the program
wasmer demoprj.wasm
Which will display:
10 + 20 = 30
10 x 20 = 200
30 / 10 = 3
Fibonacci(16):1597