I am writing a native addon for NodeJS. How can I use an environment variable as a constant at compile time? That is, "inject" a constant in to the NodeJS C++ addon from an environment variable set during node-gyp build
or npm install
. I found this answer , however as far as I can see, there is no equivalent option for passing through variables to node-gyp
I found that the defines
block and variable expansion in binding.gyp will achieve what I'm after:
{
"targets": [
{
"target_name": "targetName",
"sources": [ "source.cc" ],
"defines": [
'MY_DEFINE="<!(echo $MY_ENV_VAR)"'
]
}
]
}
Then MY_DEFINE
is available with value equal to whatever MY_ENV_VAR
set set to at compile time.
Normally when you create a Makefile yourself you can pass options to the compiler like:
-D name=definition
which is equivalent of having this in the source code:
#define name "definition"
so using:
-D NAME=$NAME
would put the NAME
environment variable as a NAME
constant in the compiled source code.
But with node-gyp
the Makefile is generated for you, see:
You may need to change the generated Makefile after you run:
node-gyp configure
but before you run:
node-gyp build
or you can make a simple library which entire purpose would be to have a given value defined that would be used by your Node addon.
Another option would be to have a script that does something like:
echo "#define NAME \"$NAME\"" > config.h
and you can then include the config.h
file by your Node native addon or any other code written in C or C++.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.