使用Cmake-js构建基于node-addon-api的C++扩展
基于node-addon官方的eample改造测试:https://github.com/nodejs/node-addon-examples
Cmake-js的github给了一个例子,但是是基于NAN的,而不是node-addon-api:https://github.com/cmake-js/cmake-js/wiki/TUTORIAL-01-Creating-a-native-module-by-using-CMake.js-and-NAN
它里面给了一个CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8)# Name of the project (will be the name of the plugin)
project(addon)# Build a shared library named after the project from the files in `src/`
file(GLOB SOURCE_FILES "src/*.cc" "src/*.h")
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})# Gives our library file a .node extension without any "lib" prefix
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")# Essential include files to build a node addon,
# You should add this line in every CMake.js based project
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_JS_INC})# Essential library files to link to a node addon
# You should add this line in every CMake.js based project
target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})
直接复制过来,然后编译:
npm install -g cmake-js
npm install node-addon-api
cmake-js build
报错:
原因是没找到hello.cc里引用的头文件napi.h
解决办法一: 直接指定这个头文件的路径
参考:https://github.com/cmake-js/cmake-js/issues/309
target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_SOURCE_DIR}/node_modules/node-addon-api")
这个方法不太好,因为得认为去指定路径。
解决办法二: 自动找
参考:http://nodejs.github.io/node-addon-examples/build-tools/cmake-js/
Modules based on node-addon-api include additional header files that are not part of Node itself. These lines instruct CMake.js where to find these files:
# Include Node-API wrappers
execute_process(COMMAND node -p "require('node-addon-api').include"WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}OUTPUT_VARIABLE NODE_ADDON_API_DIR)
string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})
这就类似于binding,gyp里的: