在 iOS 应用程序中链接静态库后架构 arm64 的未定义符号

zfg*_*fgo 6 c++ xcode static-libraries ios

我正在创建一个示例静态库以在我的 iOS 应用程序中使用,但是,在调用静态库的方法时,我遇到了链接器错误:

Undefined symbols for architecture arm64:
"_doMath", referenced from:
  _doMathInterface in libTestMain.a(Test.o)
 (maybe you meant: _doMathInterface)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)

这是静态库的结构:

我有一个头文件 Test.h:

#import <Foundation/Foundation.h>

@interface Test : NSObject

int doMathInterface(int a, int b);

@end
Run Code Online (Sandbox Code Playgroud)

及其实现 Test.m :

#import "Test.h"
#include "PaymentAPI.h"

@implementation Test

int doMathInterface(int a, int b){
    return doMath(a, b);
}

@end
Run Code Online (Sandbox Code Playgroud)

在 PaymentAPI.h 中:

#ifndef PaymentAPI_h
#define PaymentAPI_h

int doMath(int a, int b);

#endif /* PaymentAPI_h */
Run Code Online (Sandbox Code Playgroud)

最后在 PaymentAPI.cpp 中:

#include <stdio.h>
#include "PaymentAPI.h"

int doMath(int a, int b){
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它是一个非常简单的静态库,但我无法弄清楚为什么会发生此链接器错误,我在应用程序的构建阶段的“链接二进制文件与库”中添加了静态库。

这是应用程序文件的屏幕截图:

在此处输入图片说明

并且构建设置中的搜索路径配置也是正确的,我相信:

在此处输入图片说明

这是静态库项目的一些构建设置的屏幕截图

构建阶段: 在此处输入图片说明

建筑学: 在此处输入图片说明

非常感谢。

Jus*_*Sid 2

问题是您的doMath函数被编译为 C++ 代码,这意味着函数名称会被 C++ 编译器破坏。然而,您的Test.m文件会被(目标)C 编译器使用,并且 C 不使用名称修饰。

这意味着链接器最终将寻找错误的符号。您可以通过让 C++ 编译器发出未损坏的函数名称来解决此问题。为此,您必须extern "C"在 PaymenAPI.h 中使用,如下所示:

#ifndef PaymentAPI_h
#define PaymentAPI_h

#ifdef __cplusplus
extern "C" {
#endif

int doMath(int a, int b);

#ifdef __cplusplus
}
#endif

#endif /* PaymentAPI_h */
Run Code Online (Sandbox Code Playgroud)

要获得完整的解释,您可以查看这个SO问题和接受的答案:Combining C++ and C - how does #ifdef __cplusplus work?