且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试从Swift调用C ++代码时出现链接器错误

更新时间:2022-10-26 11:00:43

如注释中所述,错误是只有函数
声明被标记为externC,但不是定义。



所以当编译Swift源文件时,编译器创建
a对符号_getOne的引用,但是当编译Sample.cpp时,
C ++的符号__Z6getOnev被定义为。因此,链接
程序失败。



解决方案是包括Sample.cpp中的Sample.h:

  #include< stdio.h> 
#includeSample.h

int getOne()
{
return 1;
}

,以便 externC linkage-specification应用于函数定义。



一般来说,***包含相应的.c / .cpp文件/.m文件,以确保实现
匹配公共接口。


I am trying to call a simple C++ function from Swift, but I am getting the Apple Mach-O Linker Error:

My Sample.h file (C++):

#if __cplusplus
extern "C" {
#endif

    int getOne();

#ifdef __cplusplus
}
#endif

My Sample.cpp file:

#include <stdio.h>

int getOne()
{
    return 1;
}

My bridging header:

#include "Sample.h"


I am trying to call the function as simple as:

println(getOne())

Notes:

I did add the C++ library to the Project and to the build Libraries (Build phases), I tried this code with Xcode 6.2 (Swift 1.1) and with Xcode 6.3 (beta Swift 1.2), and same error occours.

I did add the bridging header to the Build settings.

I've read something about wrapping my C++ code in Obj-c, but I haven't quite been able to manage that.

Any help is appreciated.

As already stated in a comment, the error is that only the function declaration is marked extern "C", but not the definition.

So when compiling the Swift source file, the compiler creates a reference to the symbol "_getOne", but when compiling "Sample.cpp", the C++ mangled symbol " __Z6getOnev" is defined. Therefore linking the program fails.

A solution is to include "Sample.h" from "Sample.cpp":

#include <stdio.h>
#include "Sample.h"

int getOne()
{
    return 1;
}

so that the extern "C" linkage-specification is applied to the function definition as well.

It is generally good practice to include the .h file from the corresponding .c/.cpp/.m file to ensure that the implementation matches the public interface.