Home > other >  Access inline C function from C
Access inline C function from C

Time:01-18

I'm trying to create C funciton wrappers for C and my goal is to make them inline. All the solutions on the internet say that when making an inline function in a library, just put the function definition in the header file. This won't work in this case though, since the functions contain code that will only compile in C .

This example demonstrates the situation:

// box_c.cpp
#include "box.h"

extern "C" Square *new_Square(int width, int height){
    return new Square(width, height);
}



// box_c.h
void *new_Square(int width, int height);



// main.c
#include "box_c.h"

int main(void){
    void *s = new_Square(5, 5);
}


Wold it be possible to make new_Square inline in this case? (The wrapper is a static library).

CodePudding user response:

Inlining means the compiler of the source where it is inlined needs to understand it on some level. C compilers don't understand C new. You can't do this. Leave it non-inlined, so a compiled version of the code can be linked without the compiler needing to understand C natively.

If the code (both library and final executable) is compiled with LTO enabled, it's possible the linker might inline the code at that point, but there are no guarantees there.

CodePudding user response:

Obviously in general you cannot inline C code inside C code, they are two different languages.

So, either

  • force the explicit instantiation of the C function in the compiled library,

  • ensure that the C function is code-compatible with C and leave it in the header file as inline.

  •  Tags:  
  • c c
  • Related