Search code examples
c++spidermonkey

Embedding SpiderMonkey JS


I'm working on a C++ application. I would like to embed SpiderMonkey in the application.

I'm working with CMake, but I couldn't get that build. So, in an attempt to reduce complications, I tried the example code on this page. This wouldn't link using cmake or gcc from the command line.

So, even simpler, just to ensure I can link properly I am trying to get the following to work. From the command line with gcc:

g++ --std=c++11 
  -I/home/thetasinner/moz/js/src/build_DBG.OBJ/dist/include     
  -L/home/thetasinner/moz/js/src/build_DBG.OBJ/js/src -DDEBUG 
  -Wl,--verbose -lmozjs-54a1 -lm -lz -ldl test.cpp -o test

On the following minimal code example:

#include <iostream>
#include <stdexcept>
#include "jsapi.h"
#include "js/Initialization.h"

int main(int argc, char** args) {
  if (!JS_Init()) {
    throw std::runtime_error("failed to initialise.");  
  }

  std::cout << "It's alive!\n";

  JS_ShutDown();
  return 0;
}

Even this doesn't link. I get the errors

/tmp/ccqjx5RY.o: In function `main':
  custom.cpp:(.text+0xf2): undefined reference to `JS_ShutDown()'
/tmp/ccqjx5RY.o: In function `JS_Init()':
  custom.cpp:(.text._Z7JS_Initv[_Z7JS_Initv]+0xa): undefined reference to
      'JS::detail::InitWithFailureDiagnostic(bool)'
collect2: error: ld returned 1 exit status

The headers are found and the linker is finding the mozjs library

attempt to open /home/thetasinner/moz/js/src/custom_build_DBG.OBJ/js/src 
  /libmozjs-54a1.so succeeded
-lmozjs-54a1 (/home/thetasinner/moz/js/src/custom_build_DBG.OBJ/js/src
  /libmozjs-54a1.so)

I am working on Linux (Ubuntu 16.04 and Debian 8.7 tried) because that's where the build tools are. I don't even want to touch Window's yet.

The 'js' executable built in the spidermonkey build works fine, which I assume has the lib I'm trying to link inside it. So I would have thought the lib itself is built okay.

Can anybody help me resolve these linker errors? There are lots of answers to questions about much older versions of SpiderMonkey, but there's nothing for more recent versions. I'm interested in version 45 (which I've tried with very similar errors) or the tip version 52. I'm comfortable enough digging around in the code working out how to do what I want with it once it builds, hence the interest in the latest version which isn't properly documented, I'm just completely stumped with the building step.


Solution

  • I suspect it's just an ordering problem on the command line:

    g++ --std=c++11 
    -I/home/thetasinner/moz/js/src/build_DBG.OBJ/dist/include     
    -L/home/thetasinner/moz/js/src/build_DBG.OBJ/js/src -DDEBUG 
    test.cpp -o test
    -Wl,--verbose -lmozjs-54a1 -lm -lz -ldl 
    

    Compilation first, followed by linking, with libraries in order of dependency. (My first guess was you'd neglected to mention mozjs on the command line. It took a second look to see it was just in the wrong place.)