首页 > 解决方案 > LNK2019:C++/CLI 中未解析的外部符号

问题描述

我有一个sample.c文件,其中定义了一个非静态函数

来源:sample.c

#if defined(__cplusplus)
extern "C" {
#endif

int get_sample_value()
{
    return 1000;
}

#if defined(__cplusplus)
}
#endif

有一个纯C++ SDK 项目sample_sdk,它基本上生成了几个静态库,其中get_sample_value()函数在一个源文件中使用,如下所示:

来源:sample_sdk_source.cpp

extern int get_sample_value();

static void do_processing()
{
    int sample_value = get_sample_value();
    process( sample_value );
}

上述sample.c将在另一个C++/CLI GUI 应用程序SampleViewer中编译,其中sample_sdk库包含在该应用程序中。但是在编译 SampleViewer 时,我们收到以下错误:

libsample-sdk-x86.lib(sample_sdk_source.obj):错误 LNK2019:函数“public: static void __cdecl do_processing()”中引用的未解析外部符号“int __cdecl get_sample_value()”(?get_sample_value@@YAPBUint@@XZ) ?do_processing@@SAXXZ)

我也尝试使用 SampleViewer::main.cpp 文件中的相同函数,但存在相同的错误。从 C++/CLI 环境访问 C 文件中定义为 extern 的函数时是否有任何问题?

标签: c++clinkerc++-cliextern

解决方案


The linker error says it all:

  • Your extern int get_sample_value(); declaration in C++ sets up an undefined symbol for the mangled name ?get_sample_value@@YAPBUint@@XZ
  • Your definition in sample.c defines a symbol with a non-mangled name (_get_sample_value).

To solve this, either mark your declaration in C++ with extern "C" as well, or better yet: move the declaration into a header that both sample.c and sample_sdk_source.cpp can include (with the #if defined(__cplusplus) guard)


推荐阅读