Skip to content

Instantly share code, notes, and snippets.

@wgwoods
Created October 27, 2021 21:31
Show Gist options
  • Save wgwoods/3d459a18f7a74e17340d0e310bbf19c3 to your computer and use it in GitHub Desktop.
Save wgwoods/3d459a18f7a74e17340d0e310bbf19c3 to your computer and use it in GitHub Desktop.
A crappy demo for building C to WebAssembly on macos or linux
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int is_empty(char *s) {
char c;
for (c = *s; c; s++) {
if (!isspace(c)) {
return 0;
}
}
return 1;
}
int main(int argc, char *argv[]) {
int retval = 0;
if (argc > 1) {
printf("Hello,");
for (int i=1; i<argc; i++) {
printf(" %s", argv[i]);
}
printf("!\n");
} else {
char *name = NULL;
ssize_t len = 0;
size_t cap = 0;
printf("Hi there. What's your name?\n> ");
fflush(stdout);
len = getline(&name, &cap, stdin);
if (len < 0) {
fprintf(stderr, "Something went wrong! Sorry :(\n");
return 1;
}
if (is_empty(name)) {
printf("You don't have a name? That's cool, me either.\n");
} else {
name[len-1] = '!'; // replace trailing "\n" with a null
printf("Hello, %s\n", name);
}
free(name);
}
}
CC=clang
CFLAGS=-Os
WASI_VERSION=12
WASI_VERSION_FULL=$(WASI_VERSION).0
ifeq ($(OS),Windows_NT)
HOST_OS=mingw
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
HOST_OS = linux
endif
ifeq ($(UNAME_S),Darwin)
HOST_OS = macos
endif
endif
WASI_RELEASE_BASEURL=https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-$(WASI_VERSION)
WASI_SDK_TARBALL=wasi-sdk-$(WASI_VERSION_FULL)-$(HOST_OS).tar.gz
WASI_SDK_DIR=wasi-sdk-$(WASI_VERSION_FULL)
WASI_SYSROOT=$(WASI_SDK_DIR)/share/wasi-sysroot
WASI_CC=$(WASI_SDK_DIR)/bin/clang --sysroot=$(WASI_SYSROOT)
all: hello hello.wasm
hello: hello.c
$(CC) $(CFLAGS) $< -o $@
hello.wasm: hello.c $(WASI_SDK_DIR)
$(WASI_CC) --sysroot=$(WASI_SYSROOT) $< -o $@
$(WASI_SDK_DIR):
curl --proto '=https' --tlsv1.2 -sSLf $(WASI_RELEASE_BASEURL)/$(WASI_SDK_TARBALL) | tar -zxvf -
clean:
@rm -f hello hello.wasm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment