如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
- 使用cmake-js编译NodeJS C++插件
- 1. 安装cmake-js
- 2. 编写addon.cpp
- 3. 编写CMakeLists.txt
- 4. 编译.node
- 5. 编写index.js测试.node
- 在线安装
$npm i -g cmake-js
查看cmake-js帮助
$ cmake-js -h
- 离线安装
头文件下载
https://nodejs.org/dist/v12.13.0/node-v12.13.0-headers.tar.gz
库文件下载(仅windows)
https://nodejs.org/dist/v12.13.0/win-x64/node.lib
linux
~/.cmake-js/node-x64/v12.13.0/include
$ tree
.cmake-js
└── node-x64
└── v12.13.0
└── include
└── node
windows
~/.cmake-js/node-x64/v12.13.0/include
$ tree .cmake-js +--- node-x64 | +--- v12.13.0 | | +--- include | | | +--- node | | +--- win-x64 | | | +--- node.lib2. 编写addon.cpp
addon.cpp
#include #include3. 编写CMakeLists.txtstatic napi_value helloMethod(napi_env env, napi_callback_info info) { napi_status status; napi_value result; status = napi_create_string_utf8(env, "hello world", 11, &result); assert(status == napi_ok); return result; } static napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor desc = {"hello", 0, helloMethod, 0, 0, 0, napi_default, 0}; status = napi_define_properties(env, exports, 1, &desc); assert(status == napi_ok); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(addon)
message(STATUS "operation system is ${CMAKE_SYSTEM}")
#add_compile_options(-g)
# 设置头文件路径
include_directories(${CMAKE_JS_INC})
include_directories(.)
# 源文件列表
file(GLOB SOURCE_FILES addon.cpp)
# 生成.node文件
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
# 设置输出文件后缀
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
# 设置库依赖
target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})
4. 编译.node
$ cmake-js configure build -D5. 编写index.js测试.node
index.js
'use strict';
const addon = require('bindings')('addon');
console.log(addon.hello()); // 'hello world'
$ node index.js hello world
License
License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
Reference:
- NULL



