Reputation: 113
I am newbie in C. I am trying to pack a function say
to a struct Person
. It seems fine on single c file. (Console will print "Bye.")
// all-in-one-file.c
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
void (*say)(char *sayType);
} Person;
void person_say(char *sayType);
Person initPerson();
int main()
{
Person person = initPerson();
person.say("Bye");
return 0;
}
void person_say(char *sayType)
{
if (sayType == "Hi")
{
printf("Hi.\n");
}
else if (sayType == "Bye")
{
printf("Bye.\n");
}
else
{
printf("...\n");
}
}
Person initPerson()
{
Person per;
per.say = person_say;
return per;
}
However, the console will print "..." when I try to put the struct and function to header file.
// person.h
#ifndef _PERSON_H_
#define _PERSON_H_
typedef struct
{
void (*say)(char *sayType);
} Person;
Person initPerson();
#endif
// person.c
#include <stdio.h>
#include "person.h"
void person_say(char *sayType)
{
if (sayType == "Hi")
{
printf("Hi.\n");
}
else if (sayType == "Bye")
{
printf("Bye.\n");
}
else
{
printf("...\n");
}
}
Person initPerson()
{
Person per;
per.say = person_say;
return per;
}
// main.c
#include <stdio.h>
#include <stdlib.h>
#include "person.h"
int main()
{
Person person = initPerson();
person.say("Bye");
return 0;
}
I think I have some mistakes in header file or person.c
. But I cannot find the reason and the solution to fix this problem.
Upvotes: 1
Views: 55
Reputation: 3396
sayType == "Hi"
this compares the addresses, not the contents. You should use strcmp (sayType, "Hi")
for comparing contents of strings.
The explanation why it looks like working when they are all in one .c
file is this:
When all source is in one translation unit (that is one .c file), compiler mapped string literals with identical contents to the same address. (which is implementation defined behavior that you can not depend). Therefore, identical literals have the same address so that address comparison worked.
However, when compiled in distinct translation units, compiler has no knowledge of other translation unit while compiling one, therefore they are mapped to different addresses.
Upvotes: 1