' __declspec(dllexport) extern std::string foo; '链接器未找到

`__declspec(dllexport) extern std::string foo;` not found by linker

本文关键字:链接 foo extern declspec dllexport std string      更新时间:2023-10-16

我遇到了这里提到的同样的问题:Protobuf -拒绝链接vs2013或vs2015

我发现generated_message_util.h中的这两行可能会导致这个问题:

__declspec(dllexport) extern const ::std::string* empty_string_;
__declspec(dllexport) extern ProtobufOnceType empty_string_once_init_;

见:https://github.com/google/protobuf/blob/master/src/google/protobuf/generated_message_util.h L80

我对关键字extern不太熟悉,但在最后,试图使用该库的链接器找不到这些变量的两个定义,这是在generated_message_util.cc中完成的。

const ::std::string* empty_string_;
GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_);
void InitEmptyString() {
  empty_string_ = new string;
  ...
}

参见:https://github.com/google/protobuf/blob/master/src/google/protobuf/generated_message_util.cc#L51和以下行。

有人知道这个问题的一个很好的解决方法吗?

确保你的编译器标志和定义的预处理器符号设置正确。

__declspec(dllexport)应该设置为创建DLL,并且您的代码需要包含该定义。如果你想使用DLL,那么你需要__declspec(dllimport)

LIBPROTOBUF_EXPORT的定义见port.h文件(src/google/protobuf/stub/port.h)。它取决于LIBPROTOBUF_EXPORTS,所以如果你想要创建 DLL,确保LIBPROTOBUF_EXPORTS 定义的。如果您想要使用 DLL,请确保LIBPROTOBUF_EXPORTS 没有定义

为了识别问题,您可以在项目中插入以下代码:

#ifdef LIBPROTOBUF_EXPORTS
#error defining LIBPROTOBUF_EXPORTS only allowed on DLL creation!
#endif
#ifndef PROTOBUF_USE_DLLS
#error defining PROTOBUF_USE_DLLS is required for DLL usage!
#endif

如果符号定义错误,将导致编译错误。然后,您仍然需要修复项目设置,直到满足条件。根据目前的情况,我帮不了你。

如果条件没有触发错误,而问题仍然存在,则可能有其他事情发生,值得更详细地研究。