尝试从Swift调用C ++代码时出现链接器错误 [英] Linker error when trying to call C++ code from Swift

查看:336
本文介绍了尝试从Swift调用C ++代码时出现链接器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Swift调用一个简单的C ++函数,但我得到 Apple Mach-O链接器错误



img src =http://i.stack.imgur.com/D4ZuIm.pngalt =错误>





我的Sample.h文件(C ++):

  #if __cplusplus 
externC{
#endif

int getOne

#ifdef __cplusplus
}
#endif

My Sample.cpp file:

  #include< stdio.h> 

int getOne()
{
return 1;
}

我的桥接标题:

  #includeSample.h






我试图像下面这样简单的调用函数:

  println(getOne 

注意

我添加了C ++库到项目和构建库(构建阶段),我试过这个代码与Xcode 6.2(Swift 1.1)和Xcode 6.3(beta Swift 1.2),以及相同的错误发生。



我已经读了一些关于包装我的C ++代码



任何帮助是值得赞赏的。

解决方案

如注释中所述,错误是只有函数
声明被标记为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.

这篇关于尝试从Swift调用C ++代码时出现链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆