CodeBlanks Logo Icon CodeBlanks

Build

Learn to build native addons with node-gyp.

Build (node-gyp)

Native addons must be compiled; node-gyp is the tool that does it. The binding.gyp file defines the target, source files and compile flags. The node-gyp build command takes these and produces a .node file.

A buildConfig(target) function models this structure: it returns the target, source files and flags. Example: buildConfig('linux') returns {target: 'linux', sources: ['addon.cc'], flags: '-std=c++17'}. .sources.join(',') turns the source list into a string. The output is linux: addon.cc. This is a simple model of node-gyp's build configuration; the real binding.gyp is in JSON format but the structure is the same: target, sources, flags.

Source files

An addon is compiled from one or more C++ source files. The sources array lists these files. buildConfig('linux').sources returns ['addon.cc']. .join(',') turns it into a string.

Example: const cfg = buildConfig('linux'). cfg.target is 'linux', cfg.sources is ['addon.cc'], cfg.flags is '-std=c++17'. console.log(cfg.target + ': ' + cfg.sources.join(',')) prints linux: addon.cc. With multiple sources it would be ['addon.cc', 'utils.cc'] and join would give addon.cc,utils.cc. node-gyp takes this list, compiles each file, then links them. This model summarizes the build target in a single object.

Practice Write the build configuration

Write function buildConfig(target). Return {target: target, sources: ['addon.cc'], flags: '-std=c++17'}. Define const cfg = buildConfig('linux'). Print console.log(cfg.target + ': ' + cfg.sources.join(',')).

Starter code

index.js
// Write a buildConfig function
// Return target, source files and flags
// Call with 'linux', print as 'target: sources'
// write here

Sample solution

index.js
function buildConfig(target) {
  return {target: target, sources: ['addon.cc'], flags: '-std=c++17'};
}
const cfg = buildConfig('linux');
console.log(cfg.target + ': ' + cfg.sources.join(','));

Expected output

linux: addon.cc

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the flags value

Question
return {target: target, sources: ['addon.cc'], ____: '-std=c++17'};
Answer
return {target: target, sources: ['addon.cc'], flags: '-std=c++17'};

Explanation: flags carries the compile flags.

2 Match each concept to its description

Term Meaning
node-gyp Build tool
binding.gyp Build configuration
sources C++ file list
.node Compiled addon file

3 What does buildConfig('linux').sources return?

index.js
buildConfig('linux').sources
  • 'linux'
  • 'addon.cc'
  • '-std=c++17'
  • ['addon.cc'] Correct answer

Explanation: sources is an array: ['addon.cc'].

All lessons in Expert