Running luajit object file from C

后端 未结 2 822
清歌不尽
清歌不尽 2020-12-09 23:11

From the documentation: http://luajit.org/running.html

luajit -b test.lua test.obj                 # Generate object file
# Link test.obj with your applicati         


        
2条回答
  •  一整个雨季
    2020-12-09 23:51

    main.lua

    print("Hello from main.lua")
    

    app.c

    #include 
    
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"
    
    int main(int argc, char **argv)
    {
      int status;
      lua_State *L = luaL_newstate();
      luaL_openlibs(L);
      lua_getglobal(L, "require");
      lua_pushliteral(L, "main");
      status = lua_pcall(L, 1, 0, 0);
      if (status) {
        fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
        return 1;
      }
      return 0;
    }
    

    Shell commands:

    luajit -b main.lua main.o
    gcc -O2 -Wall -Wl,-E -o app app.c main.o -Ixx -Lxx -lluajit-5.1 -lm -ldl
    

    Replace -Ixx and -Lxx by the LuaJIT include and library directories. If you've installed it in /usr/local (the default), then most GCC installations will find it without these two options.

    The first command compiles the Lua source code to bytecode and embeds it into the object file main.o.

    The second command compiles and links the minimal C application code. Note that it links in the embedded bytecode, too. The -Wl,-E is mandatory (on Linux) to export all symbols from the executable.

    Now move the original main.lua away (to ensure it's really running the embedded bytecode and not the Lua source code file) and then run your app:

    mv main.lua main.lua.orig
    ./app
    # Output: Hello from main.lua
    

提交回复
热议问题