Swift Static Library based on C++ sources: linker command failed error: ld: symbol(s) not found for architecture x86_64 clang

Swift Static Library based on C++ sources: linker command failed error: ld: symbol(s) not found for architecture x86_64 clang

我有基于 C++ 的 swift 静态库调用:FooCppBasedSwiftLibrary

// ...100-500 lines error log above...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

TLDR: Use linker flag: -lc++ or -lstdc++
// You can skip to the "The Endgame" section below

初步解决方法

背景

在浏览大量论坛寻求解决方案时,我遇到了某人的想法:

注意:本文引用自类似问题的线程(与我的问题相同),但不同之处在于:在 ObjC 项目中导入 Swift 静态库

This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.

So basically all you have to do is add at least one .swift file to that compile list and it will include the Swift libraries for you. It doesn't even need to have any code or values in it, it can be an empty file.

解决方法:

所以考虑到相同的逻辑,我想,我的客户端应用程序项目,Swift 基于:

How will it know that static library libFooCppBasedSwiftLibrary.a has used or needs (not sure what's correct word here) standard C++ libraries, like for eg: std::

所以解决这个问题的方法是:

  • 在我的客户端应用程序项目中单击了 root/any 文件夹 "New File..." -> Select "C++ File" ->设置任意文件名->勾选"Also create a header file"->Next-> Create -> 你会得到提示“你想配置一个 Objective-C 桥接头吗?”,点击 "Create Bridging Header" 按钮

你是完成,现在构建你的应用程序它应该工作正常!

这充其量是一种解决方法,但不确定是否有任何构建设置可以强制执行此操作而不是添加空 C++ 文件。

The Endgame:

经过进一步挖掘,我找到了完美的解决方案

首先,ignore/undo 最初的解决方法,我们不再需要它了

转到客户端应用程序项目的构建设置(对于应用程序目标)并在 Other linker flags 中添加 -lc++-lstdc++ 并构建应用程序,完成!

What to chooese -lc++ or -lstdc++?

Check "C++ standard library"/ CLANG_CXX_LIBRARY setting in build settings

if its libc++ then use: lc++ in Other linker flags

else if its libstdc++ then use: lstdc++ in Other linker flags

我假设这是明确告诉 linker 正确地 link .a 带有给定标准 C++ 库的静态库的二进制文件