使用makefile編譯nodejs模組

來源:互聯網
上載者:User

標籤: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模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.