【推荐阅读】微服务还能火多久?>>> makefile编译node插件-LMLPHP

makefile编译node插件


如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033

文章目录

环境:
系统:centos 7
node: v12.13.0


1.目录结构

$ tree
.
├── 12.13.0
│   ├── include
│   │   └── node
│   │       ├── ...
├── build
│   ├── hello.node
│   ├── hello.o
│   └── linker.lock
├── hello.cc
├── index.js
└── Makefile

其中,12.13.0文件夹为node v12.13.0版本的头文件

2.hello.cc

// hello.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "world", NewStringType::kNormal).ToLocalChecked());
}

void Initialize(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

}  // 命名空间示例

3.index.js

//hello.js

var addon = require('./build/hello.node');

console.log(addon.hello()); // 'world'

4.Makefile

CC = g++

INC_DIR= \
	-I./12.13.0/include/node \
	-I./12.13.0/src \
	-I./12.13.0/deps/openssl/config \
	-I./12.13.0/deps/openssl/openssl/include \
	-I./12.13.0/deps/uv/include \
	-I./12.13.0/deps/zlib \
	-I./12.13.0/deps/v8/include

#output dir
OUTDIR = ./build

#the moudle name
MODULE_NAME = hello.node

#target path
TARGET = $(OUTDIR)/$(MODULE_NAME)

#可以定义变量
objs = $(OUTDIR)/hello.o

# include header
CPPFLAGS += ${INC_DIR}
CPPFLAGS += -shared -fPIC -std=c++11


#LINKFALGS = -shared -pthread -rdynamic -m64 -lpthread -Wl,-soname=$(MODULE_NAME)
# mpis
LINKFALGS = -shared -pthread -rdynamic -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 $@

$(objs): $(OUTDIR)/%.o: %.cc
	$(CC) -c $(CPPFLAGS) $< -o $@

#声明clean是一个伪目标
.PHONY: clean
clean:
	-rm -rf $(OUTDIR)
	-rm -f $(TARGET)

5.结果

$ make
mkdir build
g++ -c -I./12.13.0/include/node -I./12.13.0/src -I./12.13.0/deps/openssl/config -I./12.13.0/deps/openssl/openssl/include -I./12.13.0/deps/uv/include -I./12.13.0/deps/zlib -I./12.13.0/deps/v8/include -shared -fPIC -std=c++11 hello.cc -o build/hello.o
flock ./build/linker.lock g++ -shared -pthread -rdynamic -lpthread -Wl,-soname=hello.node -o ./build/hello.node -Wl,--start-group ./build/hello.o -Wl,--end-group

$ node index.js
world

License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:
NULL

发布了234 篇原创文章 · 获赞 229 · 访问量 89万+
04-14 15:18