Search code examples
cffiluajit

How to expose a function from C executable to LuaJIT ffi


I'm trying to call C functions in luajit ffi from within the same executable but I get undefined symbol error. Why?

main.c

#include <luajit-2.0/gcclauxlib.h>
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lualib.h>

extern void my_func(void)
{
    printf("f\n");
}

const char *lua = "local ffi = require(\"ffi\")\n"
          "ffi.cdef[[\n"
          "void my_func(void);\n"
          "]]\n"
          "ffi.C.my_func()\n";

int main(int argc, char **argv)
{
    lua_State *L = luaL_newstate();

    luaL_openlibs(L);

    if (luaL_dostring(L, lua)) {
        printf("err: %s\n", lua_tostring(L, -1));
    }
    lua_close(L);

    return 0;
}

Ran with:

$ gcc main.c -lluajit-5.1
$ ./a.out   

Outputs:

err: [string "local ffi = require("ffi")..."]:5: /usr/lib/libluajit-5.1.so.2: undefined symbol: my_func

Solution

  • Found it. Just had to compile with -Wl,-E

    $ gcc main.c -Wl,-E -lluajit-5.1
    $ ./out
    f