Reputation: 5683
I'm trying to use a separate C header and implementation file in Xcode iOS/Objective-C project.
I want to use the method I implemented in main.m but I get these errors:
I've included user.h in main.m
Note that Target Membership is selected in user.c for HelloWorld. When I deselect this the errors are gone. But when I try to run the app, I get these errors at compile time:
Full size here
When I implement the struct and method in main.m it compiles and runs just fine. But I don't get it why I can't use this particular code in a separate file?
Source Code:
user.h
#ifndef HelloWorld_user_h
#define HelloWorld_user_h
typedef struct {
char *name;
int age;
char sex;
} User; //sizeof(User) = 16 bytes
void CreateAndDisplay(User *usr, char *name, int age, char sex);
#endif
user.c
#include <stdio.h>
#include <stdlib.h>
void CreateAndDisplay(User *usr, char *name, int age, char sex) {
usr->name = name;
usr->age = age;
usr->sex = sex;
printf("User address -> value:\n");
printf("Name:\t%u\t->\t%s\n", (uint)usr, *&usr->name);
printf("Age:\t%u\t->\t%i\n", (uint)&usr->age, *&usr->age);
printf("Sex:\t%u\t->\t%c\n\n", (uint)&usr->sex, *&usr->sex);
printf("User has a size of %li bytes in memory", sizeof(*usr));
}
main.m
#import <UIKit/UIKit.h>
#import "HelloWorldAppDelegate.h"
#include <stdio.h>
#include <stdlib.h>
#include "user.h"
int main(int argc, char *argv[])
{
User user1;
CreateAndDisplay(&user1, "John Doe", 24, 'm');
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([HelloWorldAppDelegate class]));
}
}
Upvotes: 1
Views: 3976
Reputation: 18363
These errors are because there are two types referenced in user.c
that haven't been declared in headers that it imports: User
(defined in user.h
) and uint
(defined in <sys/types.h>
). To resolve these errors, inside user.c
you should add the following includes:
#include "user.h"
#include <sys/types.h>
Upvotes: 1