Reputation: 1216
I want to create a static library in Objective C iOS. But in that I want to define only structure in .h file. There won't be any .m file file that.
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;
So, When I create my static library and including it into demo application. It is always showing me linker error.
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)
So, Could someone please help me in resolving this.
Thanks in Advance.
Upvotes: 2
Views: 404
Reputation: 726619
When you write this forward declaration,
extern const struct ApiResponseStruct ApiResponse;
you promise the compiler that there is a non-static definition of ApiResponse
in one of your files. It appears that none of your .m files provides this definition, so the linker complains that ApiResponse
is undefined.
Add
const struct ApiResponseStruct ApiResponse;
to one of your .m or .c files. It could be in your library or in your application, but it needs to exist in order for your project to compile properly.
How do I assign a value to ApiResponse.A = @"String"? I get an error when I try it.
You get an error because you are trying to assign it in a static context. You need to make the assignment at runtime, for example, from the application:didFinishLaunchingWithOptions:
method of your application delegate:
// 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;
}
You wouldn't be able to keep this const
, because it is not possible to provide meaningful static initialization for NSString*
fields. You should either change the header to this
extern struct ApiResponseStruct ApiResponse;
or use a different approach: make a pointer to ApiResponse
a const
, and point it statically to a non-const struct
, like this:
extern const struct ApiResponseStruct *ptrApiResponse;
In the app delegate file:
struct ApiResponseStruct ApiResponse;
const struct ApiResponseStruct *ptrApiResponse = &ApiResponse;
Users of your API would have to write ptrApiResponse->A
instead of ApiResponse.A
, but the compiler will be able to enforce const-ness.
Upvotes: 2