Linker error when trying to call C++ code from Swift

大兔子大兔子 提交于 2019-12-12 05:29:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29327312/linker-error-when-trying-to-call-c-code-from-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!