项目组有把js接入C++服务求的需求,故开始了v8接入的工作,用了一天多时间,v8才在centos环境上成功安装,过程中踩了很多坑,下面将采坑过程记录如下:
centos下编译安装v8:
查看centos版本号:
#cat /etc/redhat-release
在环境上 gcc版本(需要支持C++14)、glibc库(GLIBC-2.18)版本都OK,GN编译选项配置好,并且环境变量都配置成功的前提下,下面的V8编译、安装的脚本,功能是OK的:
编译成功后的二进制文件安装:
#v8 install mkdir -p /opt/v8/{lib,include} cd /home/ldx/software/v8-instal/v8 /bin/cp -v out.gn/x64.release/lib*.so out.gn/x64.release/*_blob.bin out.gn/x64.release/icudtl.dat /opt/v8/lib/ /bin/cp -v out.gn/x64.release/lib*.so out.gn/x64.release/*_blob.bin out.gn/x64.release/icudtl.dat /usr/lib64 /bin/cp -v out.gn/x64.release/lib*.so out.gn/x64.release/*_blob.bin out.gn/x64.release/icudtl.dat /usr/local/lib /bin/cp -vR include/* /opt/v8/include/
#并配置环境变量(PATH、LIB、LD_LIB、INCLUDE_PATH)
#使用了v8库的c++代码的编译方法 g++ -o main xx.cpp -std=c++11 -lpthread -lv8 -lv8_libplatform #生成可执行文件后,即可运行: ./main
源代码hello-world.cc(v8/sample下面的示例文件)内容如下:
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include <stdlib.h> #include <string.h> #include "include/libplatform/libplatform.h" #include "include/v8.h" int main(int argc, char* argv[]) { // Initialize V8. v8::V8::InitializeICUDefaultLocation(argv[0]); v8::V8::InitializeExternalStartupData(argv[0]); std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); // Create a new Isolate and make it the current one. v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate* isolate = v8::Isolate::New(create_params); { v8::Isolate::Scope isolate_scope(isolate); // Create a stack-allocated handle scope. v8::HandleScope handle_scope(isolate); // Create a new context. v8::Local<v8::Context> context = v8::Context::New(isolate); // Enter the context for compiling and running the hello world script. v8::Context::Scope context_scope(context); { // Create a string containing the JavaScript source code. v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "'Hello' + ', World!'", v8::NewStringType::kNormal) .ToLocalChecked();