Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Pointer to inline function

I have a static inline function defined in an H file, and at one point in a C file, I'm assigning a pointer to the function, something like this:

foo.h:

static inline void frobnicate(void) {
    // frobs something.
}

foo.c

#include "foo.h"

void execute(void (*func)(void) ) {
    func();
}

void blahBlahBlah(void) {
    execute(frobnicate);
}

bar.c

#include "foo.h"
// ...
frobnicate();

So I think what will happen here is that the compiler will inline the call to frobnicate from bar.c, but in foo.c, it will actually have to create a function to implement frobnicate, so that it can have a working pointer to it.

Can anyone confirm if my understanding is accurate, and correct me otherwise?

like image 715
brianmearns Avatar asked Jan 16 '12 20:01

brianmearns


2 Answers

Yes, you are right. When you take the pointer to the function the compiler must create an "stand alone" version where the code can be called as a normal function.

The benefit of inlining a function is that the calling code need not to be created and any other optimization can be aplied to integrate both the caller function and the inlined function. But when you need to do a regular call to the function(as when you take the address to call it latter), those optimizations are not possible anymore.

like image 174
Governa Avatar answered Sep 25 '22 08:09

Governa


inline is one of the misnomers of the C standard. Its main meaning is to be able to put the definition of a function in a header file without having to deal with "multiple definition" problems at link time.

The official way in C99 and C11 to do what you want to achieve is to have the inline definition in the header file, without the static. Since you also need the symbol to be emitted you need to tell the compiler in which compilation unit this should be. Such an instantiation can be done by have a declaration in that .c file where you omit the inline keyword.

Most naturally you could use the .c file where you actually need the symbol.

like image 38
Jens Gustedt Avatar answered Sep 25 '22 08:09

Jens Gustedt