Skip to content

SpiderMonkey in Xcode 3.2.3

I am working on a Desktop Application project that will need scripting support, specifically scripting support for people familiar with web development. Even though I have prior experience successfully embedding both Lua and Python in server side applications, I have picked Javascript for this project. Mainly for the low barrier to entry for web developers, and the massive amount of documentation for the language. I am specifically testing out SpiderMonkey right now. I struggled trying to get SpiderMonkey to compile in Xcode 3.2.3 and am documenting how I got it to work. The JSAPI User Guide had some incorrect information, so I updated it with the same information here.

First of I assume you know how to include the headers and the libjs.a library in Xcode 3.2.3. The problem came when I tried to compile the simplest of applications. The fix was you have to include a #define at before the #include "jsapi.h".
Like so:

#define XP_UNIX
#include "jsapi.h"

Also the line:

global = JS_NewGlobalObject(cx, &global_class, NULL, NULL);

was incorrect as well, it should have been:

global = JS_NewObject(cx, &global_class, NULL, NULL);

Here is the corrected code that will compile and run on Xcode 3.2.3

#define XP_UNIX
#include "jsapi.h"

/* The class of the global object. */
static JSClass global_class = {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
};

/* The error reporter callback. */
void reportError(JSContext *cx, const char *message, JSErrorReport *report)
{
    fprintf(stderr, "%s:%u:%s\n",
            report->filename ? report->filename : "<no filename>",
            (unsigned int) report->lineno,
            message);
}

int main(int argc, const char *argv[])
{
    /* JS variables. */
    JSRuntime *rt;
    JSContext *cx;
    JSObject  *global;
    
    /* Create a JS runtime. */
    rt = JS_NewRuntime(8L * 1024L * 1024L);
    if (rt == NULL)
        return 1;
    
    /* Create a context. */
    cx = JS_NewContext(rt, 8192);
    if (cx == NULL)
        return 1;
    JS_SetOptions(cx, JSOPTION_VAROBJFIX);
    //JS_SetVersion(cx, JSVERSION_LATEST);
    JS_SetErrorReporter(cx, reportError);
    
    /* Create the global object. */
    global = JS_NewObject(cx, &global_class, NULL, NULL);
    if (global == NULL)
        return 1;
    
    /* Populate the global object with the standard globals,
     like Object and Array. */

    if (!JS_InitStandardClasses(cx, global))
        return 1;
    
    //TODO app goes here
    
    /* Cleanup. */
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return 0;
}