Swift 项目中的 C++ dylib - dylib 中公开的函数的未定义符号 [英] C++ dylib in Swift project - undefined symbols for function exposed in dylib

查看:30
本文介绍了Swift 项目中的 C++ dylib - dylib 中公开的函数的未定义符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ dylib 暴露如下

C++ dylib exposes as follows

__attribute__((visibility("default"))) int addNumber(int number) {
    return 0;
}

在我的 Swift 项目中,我将导入路径目录设置为包含我的 module.map 文件的目录:

in my Swift project, I set the Import Paths dir to the dir containing my module.map file:

module MyLib {
    header "myLib.h"
    export *
}

我手动将 myLib.h 添加到我的项目中:

I manually add myLib.h to my project:

#ifndef mylib_h
#define mylib_h

int addNumber(int number);

#endif 

我的 main.swift 执行以下操作:

My main.swift does the following:

import Foundation
import MyLib

print("Hello, World!")
var result = addNumber(3)

当我编译 swift 项目时,我可以看到它链接到我的 dylib (-lMyLib),但是我收到以下错误:

When I compile the swift project, I can see that it links against my dylib (-lMyLib), but I get the following error:

体系结构 x86_64 的未定义符号:_addNumber",引用从:main.o ld 中的 _main:未找到体系结构 x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)

Undefined symbols for architecture x86_64: "_addNumber", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

所以虽然它正确链接,但它找不到符号.我已经用 nm (0000000000000d00 (__TEXT,__text) external addNumber) 和 Hopper 验证了这个函数确实存在于 dylib 中.

So although it's linking correctly, it can't find the symbols. I've verified both with nm (0000000000000d00 (__TEXT,__text) external addNumber) and Hopper that this function does exist in the dylib.

推荐答案

在C++库中,你的函数必须用extern "C"对于 C 链接:

In the C++ library, your function must be marked with extern "C" for C linkage:

extern "C" __attribute__((visibility("default"))) int addNumber(int number) {
    return 0;
}

这样编译器就不会破坏导出的名称.斯威夫特只能调用 C 函数,而不是 C++ 函数.

so that the compiler does not mangle the exported name. Swift can only call C functions, not C++ functions.

另见externC"的作用是什么;在 C++ 中?.

这篇关于Swift 项目中的 C++ dylib - dylib 中公开的函数的未定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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