How to create a function inside a structure in a header file and implement this function in another c source file?

Viewed 51

Here I created a main.c

#include <iostream>
#include "Header.h"
struct person_t a;
int main()
{
    a.func(1,2);
}

And I have a header called "Header.h", I define a structure in this file

struct person_t {
    char name;
    unsigned age;
    int(*func)(int, int);
};

Then I implement int(*func)(int, int); in another c file called "Source.c"

#include "Header1.h"
struct person_t a;
int add2(int x, int y)
{
    return x + y;
};

a.func = &add2;

But it seems not work, does anyone who has any idea of this question?

1 Answers

You may not use statements outside a function like this

a.func = &add2;

Remove this statement and this declaration

struct person_t a;

from Source.c.

In the header place the function declaration

int add2(int x, int y);

And in the file with main write

int main()
{
    struct person_t a;
    a.func = add2;

    a.func(1,2);
}
Related