標籤:nodejs makefile addons
使用過node-gyp編譯nodejs的addon外掛程式的人,一定很好奇,node-gyp到底幫你做了什麼事情,還有,如果我們自己做,難度到底如何。本文不作makefile檔案文法的講解,如果你不懂, 沒關係,能看懂基本流程就好。拋開node-gyp,你會發現,有些複雜的東西其實是基於很簡單的原理。
環境作業系統為centos7,已經安裝了nodejs,版本為0.10.36,其實差不多新的版本就行。編譯鏈也已經準備好,g++命令啦。
編寫代碼源檔案hello.cc,很簡單,基本和官網的hello world例子一樣。
#include <stdio.h>#include <stdlib.h>#include <node/node.h>#include <node/v8.h>using namespace v8;/** * 輸出world */Handle<Value> hello(const Arguments& args){ HandleScope scope; return scope.Close(String::New("world"));}void init(Handle<Object> exports) { exports->Set(String::NewSymbol("hello"), FunctionTemplate::New(hello)->GetFunction());}NODE_MODULE(hello, init)
當我們調用模組的hello方法的時候,希望輸出world。
Makefilemakefile的一些參數,參考了node-gyp產生的makefile,但是這個就簡單多了,看代碼
CC = g++#output dirOUTDIR = ./build#the moudle nameMODULE_NAME = hello.node#target pathTARGET = $(OUTDIR)/$(MODULE_NAME)#可以定義變數objs = $(OUTDIR)/hello.oCPPFLAGS = -shared -fPICLINKFALGS = -shared -pthread -rdynamic -m64 -lpthread -Wl,-soname=$(MODULE_NAME)all: $(OUTDIR) $(objs)flock $(OUTDIR)/linker.lock $(CC) $(LINKFALGS) -o $(TARGET) -Wl,--start-group $(objs) -Wl,--end-group$(OUTDIR):mkdir [email protected]$(objs): $(OUTDIR)/%.o: %.cc$(CC) -c $(CPPFLAGS) $< -o [email protected]#聲明clean是一個偽目標.PHONY: cleanclean:-rm -rf $(OUTDIR)-rm -f $(TARGET)
all是預設的目標,在子目錄build下產生hello.node。
編譯在目前的目錄下執行make就行。如果一切順序,在目前的目錄下會產生build目錄,裡面有我們想要的hello.node。
測試編寫測試代碼test.js
var module = require('./build/hello');var value = module.hello();console.log(value);
執行node test.js,oh,居然輸出了
world
原來,沒有node-gyp,你也可以自由的編寫nodejs的模組的。需要的僅僅是一些makefile的知識。這些資料網上也不容易找,希望能幫上大家。
使用makefile編譯nodejs模組