我是 n-api 模块的新手。在组合两个 cpp 文件时,在执行 node-gyp 配置构建时出现以下错误。
b.obj : error LNK2005: _register_a_ already defined in a.obj [e:\democppmore\build\a.vcxproj]
b.obj : error LNK2005: "struct napi_value__ * __cdecl Init(struct napi_env__ *,struct napi_value__ *
)" (?Init@@YAPEAUnapi_value__@@PEAUnapi_env__@@PEAU1@@Z) already defined in a.obj [e:\democppmore\bu
ild\a.vcxproj]
我怀疑这是由于 napi_value Init() 存在于 2 个不同的 cpp 代码中。如果是这样,我们如何克服它以及我们的 gyp 和 js 文件需要如何编写?
我有以下代码:
a.cc
-------
#include <node_api.h>
#include <assert.h>
napi_value Method(napi_env env, napi_callback_info info) {
//some code
}
#define DECLARE_NAPI_METHOD(name, func) \
{ name, 0, func, 0, 0, 0, napi_default, 0 }
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
status = napi_define_properties(env, exports, 1, &desc);
assert(status == napi_ok);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
-----------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
binding.gyp
--------------
{
"targets": [
{
"target_name": "module",
"sources": [
"./src/a.cc",
"./src/b.cc" ]
}
}
--------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------
#include <node_api.h>
#include <assert.h>
#include <stdio.h>
napi_value Add(napi_env env, napi_callback_info info) {
//some code here
}
#define DECLARE_NAPI_METHOD(name, func) \
{ name, 0, func, 0, 0, 0, napi_default, 0 }
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor addDescriptor = DECLARE_NAPI_METHOD("add", Add);
status = napi_define_properties(env, exports, 1, &addDescriptor);
assert(status == napi_ok);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)