Xcode Swift项目中调用C++代码出现链接器错误
Swift调用C++库时遇到链接器符号缺失错误
问题背景
在Swift项目中尝试调用C库,已配置头文件搜索路径,创建了桥接文件、Objective-C包装类、C++头文件和实现文件,但编译时出现arm64架构下的符号未找到错误。
已完成的配置与代码
- 桥接文件
client-Bridging-header:
#import "DongleWrapper.hpp"
- Objective-C++包装类
DongleWrapper.hpp:
#import "Dongle.hpp" @implementation DongleWrapper - (DongleWrapper*) init { dong = (void*)new Dongle; // 创建C++类实例 return self; // 返回Objective-C++实例 } - (void) generateKeyPair { Dongle* d = (Dongle*)dong; d->generateKeyPair(); // 调用C++方法 } @end
- C++头文件
Dongle.hpp:
#ifndef Dongle_hpp #define Dongle_hpp #include <stdio.h> #endif /* Dongle_hpp */ class Dongle { public: void generateKeyPair(); };
- C++实现文件
Dongle.cpp:
#include "Include/pkcs.h" void Dongle::generateKeyPair() { // 调用pkcs.h中的C函数逻辑 }
错误日志
Undefined symbols for architecture arm64: "_C_GenerateKeyPair", referenced from: Dongle::generateKeyPair() in Dongle.o "_C_Login", referenced from: Dongle::generateKeyPair() in Dongle.o "_C_Logout", referenced from: Dongle::generateKeyPair() in Dongle.o "_fl", referenced from: FindObjects(unsigned long, CK_ATTRIBUTE*, unsigned long) in Dongle.o (maybe you meant: _CNIOBoringSSL_EVP_CIPHER_flags, _CNIOBoringSSL_X509_VERIFY_PARAM_set_flags , ...) ld: symbol(s) not found for architecture arm64
解决方法
1. 添加依赖库到项目
_C_GenerateKeyPair等符号属于pkcs.h对应的底层库,需将该库的**静态库(.a)或动态库(.dylib/.framework)**添加到项目:
- 拖拽库文件到Xcode项目导航栏,勾选"Copy items if needed"
- 在
Target > Build Phases > Link Binary With Libraries中确认库已被添加
2. 验证库的架构兼容性
使用M1 Pro(arm64架构),需确保依赖库支持arm64:
- 执行命令
lipo -info /path/to/your/library.a查看库支持的架构,确认包含arm64 - 若库仅支持x86_64,可重新编译库生成arm64版本,或在Xcode中启用Rosetta编译:在Target运行选项中勾选"Open using Rosetta",或在
Build Settings > Architectures中设置Build Active Architecture Only为Yes
3. 修正头文件的C/C++兼容声明
如果pkcs.h是C语言头文件,在C++代码中引用时需要用extern "C"包裹声明,避免名称修饰导致符号不匹配:
#ifdef __cplusplus extern "C" { #endif CK_RV C_GenerateKeyPair(...); CK_RV C_Login(...); CK_RV C_Logout(...); // 其他相关函数声明 #ifdef __cplusplus } #endif
4. 检查编译配置
- 确认
Target > Build Settings > Header Search Paths中正确包含Include目录,建议使用$(SRCROOT)定位项目内路径,例如$(SRCROOT)/YourProject/Include - 确认
Dongle.cpp已添加到Target > Build Phases > Compile Sources中,避免文件未被编译
5. 排查_fl符号问题
_fl缺失通常是FindObjects函数调用了未定义的变量或函数:
- 检查
pkcs.h或相关头文件中是否声明了fl - 确认
fl的定义存在于依赖库或自定义代码中,且支持arm64架构
内容的提问来源于stack exchange,提问作者desertSniper87
相关产品推荐
相关产品推荐

