开源C++项目Google JavaScript引擎V8挑战实录,带你进入V8之旅

 


--写在开始

按照今年的计划,需要研究一个有使用价值的linux下的C++开源项目,无意中发现了V8,觉得还不错,于是记录下来,希望对大家有所帮助。V8是一个由丹麦Google开发的开源JavaScript引擎,用于Google Chrome中,Chrome是现有的浏览器中速度相对比较快的一个,这完全得益于V8的效率,另外,作为一个独立的项目,V8也可以嵌入到我们自己开发的项目中运行,查了一下才知道,前一这被大家热炒的Node.js也是基于V8的,可见V8值得大家稍微研究一番。


作为一个开源JavaScript引擎,V8是以源代码的形式开源,而我们使用的时候是以库的形式进行使用,这就涉及到源代码的编译,当然你可以上网找别人build好的libv8.a或者libv8.so,使用就是了,但是既然是学习这个库,我们有时候是需要进行代码调试的,用别人的库,有的时候调试可能会有问题,还是自己动手丰衣足食啊,呵呵,那么我们开始自己build吧。 

按照项目官方Wiki上面的介绍,我用Git clone 了一份代码,命令如下: 

git clone git://github.com/v8/v8.git v8 && cd v8 

但是当我build的时候我才发现,原来最新版的V8 build 脚本已经改成了GYP,而make dependencies 这个时候在GIT的代码库里面怎么也下不了GYP这些脚本,于是我不得不重新安装Subversion,然后用:


svn checkout http://v8.googlecode.com/svn/trunk/ v8

make dependencies

 这才拿齐了build所需要的所有文件,let’s go, V8的路径下执行如下命令:

make native library=shared

经过大约5分钟的编译,终于成功的build出来了我需要的libv8.so.

 

那么这个库是否已经成功的build好了呢,那么让我们来验证一下吧,找个最简单的demo

一下是google官方的demo,简单明了。

#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;
}

 

 将段代码存成hello_world.cpp,并执行下面命令:

g++ -I include hello_world.cpp -o hello_world libv8.so  -lpthread

 

然后执行./ hello_world 这个时候你会看到屏幕上已经输出了 Hello World!

如果对代码的某一部分感兴趣你就可以打开GDB在相应的位置设置断点,单步的走代码。

恭喜你到现在为止,你已经可以无所顾忌的开始V8之旅啦。
posted @ 2012-04-02 22:03  SolidMango  阅读(10038)  评论(6编辑  收藏  举报