2

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0983
  • 31
  • 3
  • 1
    Please describe the problem better than "not work". Provide the specific error or incorrect behaviour you observe. But for starters, `a.func = &add2;` is invalid C as non-initialiser assignment statements must be inside a function. – kaylum Jul 31 '22 at 11:32
  • `struct person_t a;` in 2 different compilation units (files) are 2 different variables. `a.func = &add2;` can't exist outside of a function body. – tevemadar Jul 31 '22 at 11:34
  • Thanks for your suggestions. I will describe more detail about what behaviour I observe. And finally I just solved my question – 0983 Jul 31 '22 at 12:11

1 Answers1

0

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);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335