我想在 Objective C iOS 中创建一个静态库。但我只想在 .h 文件中定义结构。不会有任何 .m 文件。
struct ApiResponseStruct
{
__unsafe_unretained NSString * const A;
__unsafe_unretained NSString * const B;
__unsafe_unretained NSString * const C;
__unsafe_unretained NSString * const D;
};
extern const struct ApiResponseStruct ApiResponse;
所以,当我创建静态库并将其包含到演示应用程序中时。它总是向我显示链接器错误。
Undefined symbols for architecture armv7:
"_ApiResponse", referenced from:
-[TestLib setApiResponse] in libTestLib.a(TestLib.o)
-[TestLib getApiResponse] in libTestLib.a(TestLib.o)
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
那么,有人可以帮我解决这个问题吗?
提前致谢。
最佳答案
当您编写此前向声明时,
extern const struct ApiResponseStruct ApiResponse;
您向编译器保证,您的某个文件中存在 ApiResponse
的非静态定义。您的 .m 文件似乎都没有提供此定义,因此链接器提示 ApiResponse
未定义。
添加
const struct ApiResponseStruct ApiResponse;
到您的 .m 或 .c 文件之一。它可能位于您的库或应用程序中,但它需要存在才能使您的项目正确编译。
How do I assign a value to ApiResponse.A = @"String"? I get an error when I try it.
您收到错误是因为您尝试在静态上下文中分配它。您需要在运行时进行分配,例如,通过应用程序委托(delegate)的 application:didFinishLaunchingWithOptions:
方法进行分配:
// Define your struct outside the method
struct ApiResponseStruct ApiResponse;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
... // Your regular "didFinishLaunchingWithOptions' code...
ApiResponse.A = @"Quick";
ApiResponse.B = @"Brown";
ApiResponse.C = @"Fox";
ApiResponse.D = @"Jumos";
return YES;
}
您将无法保留此 const
,因为无法为 NSString*
字段提供有意义的静态初始化。您应该将标题更改为此
extern struct ApiResponseStruct ApiResponse;
或者使用不同的方法:将指向 ApiResponse
的指针设置为 const
,并将其静态指向非 const struct
,例如这个:
extern const struct ApiResponseStruct *ptrApiResponse;
在应用程序委托(delegate)文件中:
struct ApiResponseStruct ApiResponse;
const struct ApiResponseStruct *ptrApiResponse = &ApiResponse;
API 的用户必须编写 ptrApiResponse->A
而不是 ApiResponse.A
,但编译器将能够强制执行常量性。
关于ios - 如何将仅包含结构的.h文件包含到静态库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20783272/