This document introduces some key V8 concepts and provides a hello
world
example to get you started with V8 code.
This document is intended for C++ programmers who want to embed the V8 JavaScript engine within a C++ application.
Let's look at a Hello World example that takes a JavaScript statement as a string argument, executes it as JavaScript code, and prints the result to standard out.
int main(int argc, char* argv[]) {
// Create a string containing the JavaScript source code.
String source = String::New("'Hello' + ', World'");
// Compile the source code.
Script script = Script::Compile(source);
// Run the script to get the result.
Value result = script->Run();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
To actually run this example in V8, you also need to add handles, a handle scope, and a context:
The following example is the same as the one above, except now it includes handles, a context, and a scope - it also includes a namespace and the v8 header file:
#include <v8.h>
using namespace v8;
int main(int argc, char* argv[]) {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Persistent<Context> context = Context::New();
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Handle<String> source = String::New("'Hello' + ', World!'");
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Dispose the persistent context.
context.Dispose();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
Handles, garbage collection, contexts, and scopes are discussed in greater detail in the Embedder's Guide.
Follow the steps below to run the example yourself:
hello_world.cpp in
the V8 directory that was created during your V8 build.hello_world.cpp, linking to the libv8.a library
created in the build process. For example, on Linux using the GNU compiler:g++ -Iinclude hello_world.cpp -o hello_world libv8.a -lpthreadhello_world executable file at the command line../hello_worldHello, World!.Of course this is a very simple example and it's likely you'll want to do more than just execute scripts as strings! For more information see the Embedder's Guide.