Compile C/C++ to Wasm WASI
Now that you have Wasienv installed, let's get our hands dirty!
Wasienv comes with C/C++ support preinstalled, so you just need to run one command to get things running πŸ™‚

Compiling C files with `wasic`

If you want to compile a simple C example, you can just create the following:
example.c
fizzbuzz.c
1
#include <stdio.h>
2
​
3
int main(int argc, char **argv)
4
{
5
if (argc < 2) {
6
printf("Hello, WASI!\n");
7
} else {
8
printf("Hello, %s!\n", argv[1]);
9
}
10
}
Copied!
1
// CPP program to print Fizz Buzz
2
#include <stdio.h>
3
​
4
int main(void)
5
{
6
int i;
7
for (i=1; i<=100; i++)
8
{
9
// number divisible by 3 and 5 will
10
// always be divisible by 15, print
11
// 'FizzBuzz' in place of the number
12
if (i%15 == 0)
13
printf ("FizzBuzz\t");
14
​
15
// number divisible by 3? print 'Fizz'
16
// in place of the number
17
else if ((i%3) == 0)
18
printf("Fizz\t");
19
​
20
// number divisible by 5, print 'Buzz'
21
// in place of the number
22
else if ((i%5) == 0)
23
printf("Buzz\t");
24
​
25
else // print the number
26
printf("%d\t", i);
27
​
28
}
29
​
30
return 0;
31
}
Copied!
Now that you have this file created, you can execute wasicc
1
wasicc example.c -o example.wasm
Copied!
Et voilΓ‘... you will have a new file example.wasm ready to be executed with your favorite WebAssembly runtime!
1
$ wasmer example.wasm
2
Hello, WASI!
Copied!

Did you know?

You can also execute the example.wasm file in your browser or in Node.js using @wasmer/wasi. Check out the examples on how to do it!

Compiling C++ files with `wasic++`

Wasienv also allows you to compile C++ files to Wasm WASI, just run it with wasic++

Using Configure and Make

In some projects, there might be already ./configure files that will configure the system (creating a Makefile normally) to compile a certain project.
If you want to use Wasienv there, you just need to wrap your ./configure call with wasiconfigure!
1
wasiconfigure ./configure
Copied!
Wasienv also has a wrapper for Makefiles
1
wasimake make
Copied!
Here's an example of a C Project that was compiled to Wasm WASI with wasienv:

Using CMake

Similarly to configure and make, we also have another command that will automatically compile all your projects made with CMake
1
wasicmake cmake .
2
make
Copied!
Here's an example project: quickjs that was compiled to WebAssembly WASI thanks to Wasienv!
And the build.sh file they used for generating the wasm file:
1
#!/bin/bash
2
​
3
# Install wasienv
4
curl https://raw.githubusercontent.com/wasienv/wasienv/master/install.sh | sh
5
​
6
mkdir -p build
7
cd build
8
wasimake cmake ..
9
cd ..
10
make -C build
Copied!
Last modified 1yr ago