1# node-gyp 2 3C++ code needs to be compiled into executable form whether it be as an object 4file to linked with others, a shared library, or a standalone executable. 5 6The main reason for this is that we need to link to the Node.js dependencies and 7headers correctly, another reason is that we need a cross platform way to build 8C++ source into binary for the target platform. 9 10Until now **node-gyp** is the **de-facto** standard build tool for writing 11Node.js addons. It's based on 's **gyp** build tool, which abstract away 12many of the tedious issues related to cross platform building. 13 14**node-gyp** uses a file called ```binding.gyp``` that is located on the root of 15your addon project. 16 17```binding.gyp``` file, contains all building configurations organized with a 18JSON like syntax. The most important parameter is the **target** that must be 19set to the same value used on the initialization code of the addon as in the 20examples reported below: 21 22### **binding.gyp** 23 24```gyp 25{ 26 "targets": [ 27 { 28 # myModule is the name of your native addon 29 "target_name": "myModule", 30 "sources": ["src/my_module.cc", ...], 31 ... 32 ] 33} 34``` 35 36### **my_module.cc** 37 38```cpp 39#include <napi.h> 40 41// ... 42 43/** 44* This code is our entry-point. We receive two arguments here, the first is the 45* environment that represent an independent instance of the JavaScript runtime, 46* the second is exports, the same as module.exports in a .js file. 47* You can either add properties to the exports object passed in or create your 48* own exports object. In either case you must return the object to be used as 49* the exports for the module when you return from the Init function. 50*/ 51Napi::Object Init(Napi::Env env, Napi::Object exports) { 52 53 // ... 54 55 return exports; 56} 57 58/** 59* This code defines the entry-point for the Node addon, it tells Node where to go 60* once the library has been loaded into active memory. The first argument must 61* match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures 62* that the argument will be correct, as long as the module is built with 63* node-gyp (which is the usual way of building modules). The second argument 64* points to the function to invoke. The function must not be namespaced. 65*/ 66NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) 67``` 68 69## **node-gyp** reference 70 71 - [Installation](/package/node-gyp#installation) 72 - [How to use](/package/node-gyp#how-to-use) 73 - [The binding.gyp file](/package/node-gyp#the-bindinggyp-file) 74 - [Commands](/package/node-gyp#commands) 75 - [Command options](/package/node-gyp#command-options) 76 - [Configuration](/package/node-gyp#configuration) 77 78Sometimes finding the right settings for ```binding.gyp``` is not easy so to 79accomplish at most complicated task please refer to: 80 81- [GYP documentation](/index.md) 82- [node-gyp wiki](/node-gyp/wiki) 83