I have 4 files:
main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "main.h"
int main() {
struct Fun *fun = (struct Fun*)malloc(sizeof(struct Fun));
fun->a = 2;
fun->b = 12;
fun->Func = Plus();
int result = fun->Func(fun, 8);
printf("%d\n", result);
return 0; }
main.h
#ifndef MAN_H_
#define MAN_H_
struct Fun {
int a;
int b;
int (*Func)(struct Fun *x,int y);
};
header.c
#include "header.h"
int Plus(struct Fun *x, int y) {
return x->a * x->b + y; };
header.h
#ifndef HEADER_H_
#define HEADER_H_
#include "man.h"
#endif /* HEADER_H_ */
when I build, I get a warning:
../main.c:12:5: warning: implicit declaration of function ‘Plus’ [-Wimplicit-function-declaration]
../main.c:12:15: warning: assignment makes pointer from integer without a cast [enabled by default]
if I run, it has no result.
But when I put all the code to main.c and edit fun->Func = Plus(); to fun->Func = Plus; it works fine: no warning, and the result is 32.
You should provide a function signature for
Plusin header.h, and also add an#include "header.h"in main.c, so that something is known about thePlusfunction when it’s used in main.c.In header.h:
Without such a signature, when compiling main.c the compiler makes assumptions about the function: an implicit declaration. This implicit declaration won’t match the actual function definition.
Also, changing
fun->Func = Plus();tofun->Func = Plus;is still necessary: the first form assigns to your function pointer the result of an attempted function call, the second form is the correct way to assign a function pointer.Finally, this is likely just a cut/paste omission, but main.h is missing an
#endif.