How can I conditionally compile code for emscripten?
Asked Answered
C

3

18

Working with a codebase which supports building for multiple Operating Systems, it is only sensible, where modifications for Emscripten are required, to integrate them into the same codebase, with the assistance of conditional compilation to let it continue to work in other environments.

There doesn't seem to be any documentation on the topic, though, which seems very poor to me, nor can I find any questions about it, which seems very surprising to me—I expected it to be well-trodden and -documented territory.

How can I do this?

(I have looked at tools/shared.py, this seems to suggest that #ifdef EMSCRIPTEN or #ifdef __EMSCRIPTEN__ could be used; I'm still asking this question to determine if I am correct, if this is the correct way of doing it, perhaps even which should be used.)

Camel answered 12/6, 2013 at 7:18 Comment(0)
S
20

According to Detecting Emscripten in preprocessor, the correct define to use is __EMSCRIPTEN__.

In October 2016, a strict build mode was introduced which, when enabled, removes the EMSCRIPTEN define. Therefore it is not recommended to use EMSCRIPTEN even though it still works in non-strict build mode.

Spalato answered 6/1, 2017 at 14:54 Comment(0)
S
7

#ifdef EMSCRIPTEN is the prefered way AFAIK.

Before cluttering your source code with #ifdefs, think about whether it would not make more sense to have certain platform dependent files and let the build tool do the work.

Also, emscripten already defines LINUX, because it handles very much like a Linux system. Normally this behavior already fixes most of the need for platform handling.

Shep answered 12/6, 2013 at 15:56 Comment(0)
M
2

This is my current solution:

  • I have a linux Makefile with the usual target, it links a previously generated static library and outputs an executable.

  • The code acts upon the WEB define with ifdefs.

  • The Makefile for the library acts upon the TARGET enviroment variable for the platform specific sources:

    ifeq ($(TARGET),WEB)
        MODULES = RenderingEngine2.o RenderingEngine1.o WebApp.o main.o
    else
        MODULES = RenderingEngine2.o RenderingEngine1.o LinuxApp.o main.o
    endif
  • Along the Makefile there is a bash script called emscripten.sh with the following content:
    #!/bin/bash

    make TARGET="WEB" CXX="em++ -DWEB" AR="emar" modules
    make TARGET="WEB" CXX="em++ -DWEB" AR="emar"
    emcc --preload-file assets -o bin/helloArrow.html bin/helloArrow bin/lib.o
    firefox bin/helloArrow.html
  • Compile and execute with ./emscripten.sh

NOTE: emscripten doesn't seem to like .a extension in static libraries so name you library with .o extension.

Malaguena answered 16/6, 2013 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.