Swift 和 C++ 在 Xcode 中桥接

Swift and C++ bridging in Xcode

本文关键字:桥接 Xcode C++ Swift      更新时间:2023-10-16

error 机器信息: macOS 10.13.5 Xcode 9.4 斯威夫特 4.1 默认 c++ 编译器

我创建了简单的 swift 项目,只是添加了带有标头的 c++ 文件,Xcode 为我创建了桥接标头。我已经初始化了.cpp文件中的基本功能,将原型写入 .hpp 文件,并在桥接标头中包含 .hpp 文件。当我开始输入文件时.swift一切似乎都正常:我的 cpp 函数名称在文件中的建议.swift适当的位置,并且没有警告或错误。但是,当我尝试构建这个项目时,并得到了以下结果: 建筑的未定义符号x86_64: "_get",引用自: _main在main.o

以下是源代码:

// main.swift
import Foundation
print("Hello, World!")
var number = get();
// cppBackend.cpp
int get()
{
return 1;
}
// cppBackend.hpp
int get();
// test-Bridging-Header.h
#include "cppBackend.hpp"

//cppBackend.hpp second version
#ifdef _cplusplus
extern "C"
{
#endif

#include <stdio.h>
int get();
#ifdef _cplusplu
}
#endif

目前 Swift 和 C++ 之间没有互操作。你可以很容易地做 ObjC 和 C,但C++你要把你的C++代码包装在 ObjC 中。