Search code examples
cstaticfunction-pointersfunction-definitionlinkage

Use function from other C file by a function pointer


First of all, I'm not sure if the title describes well the problem, feel free to change or suggest a more fitting heading.

I have the following problem: I need to pass a function pointer to some struct. When I define the function in the same file, this works perfectly fine. See here:

static void a_func(int param1, /*...*/) {
    //...
}

static const struct bt_mesh_handlers my_handlers = {
    .set = a_func,
    // ...
};

When I now define this function in another file, I can't get it to work: the header file (include guards are not shown here):

//function declaration:
void a_func(int param1, /*...*/);

the c file:

//function definition (this was defined wrongly as static before)
void a_func(int param1, /*...*/) {
    //...
}

in the main-file:

#include "myheader.h"

static const struct bt_mesh_handlers my_handlers = {
    .set = a_func,
    // ...
};

When I outsource my function to another file, I get the following error during build:

undefined reference to `a_func'

I already did some research and I'm relatively sure that in the file where a_func is defined, there automatically is generated a function pointer with the same name. Consequently, I can use that pointer to hand over my function to the struct.

But I don't know how to get that function pointer from the outsourced file into my main file. What would a good solution look like?


Solution

  • Remove static from the declarations of a_func, including its definition.

    In this context, static gives the identifier a_func internal linkage, meaning uses of the name will only be linked to a definition of the name in the same translation unit (the source file being compiled, including all files it includes directly or indirectly).

    To link to a name defined in another translation unit, you want external linkage. That is the default for functions, so removing static will give you external linkage.

    I already did some research and I'm relatively sure that in the file where a_func is defined, there automatically is generated a function pointer with the same name.

    The name of a function refers to the function. It designates the function. In C, a function designator is automatically converted to a pointer to the function, except when it is the operand of sizeof or unary &. There is no special or separate “generation” of a function pointer with the same name as the function in the file where it is defined. The compiler, linker, and/or program loader work together to know where the function is and to generate appropriate instructions to use the function or to provide its address.