1

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.

1
  • Tip, don't cast the return value of malloc. Commented Sep 27, 2012 at 14:51

1 Answer 1

4

You should provide a function signature for Plus in header.h, and also add an #include "header.h" in main.c, so that something is known about the Plus function when it's used in main.c.

In header.h:

int Plus(struct Fun *, int);

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(); to fun->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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.