使用源码编译 Lua 并创建 C 模块

我思考着从源代码中编译 Lua,然后创建一个 C 模块。 我已经成功编译了 Lua,但是我无法构建我的 C 模块。

所以我这样编译了 Lua:

gcc -o Lua *.c -Os -std=c99

像这样编译我的模块:

gcc -Wall -bundle -undefined dynamic_lookup -o module.so -I. module.c

但是这里有一些错误:

Undefined symbols for architecture x86_64:
  "_lua_pushcclosure", referenced from:
      _luaopen_module in module-fb0b1f.o
  "_lua_pushnumber", referenced from:
      _super in module-fb0b1f.o
  "_lua_setglobal", referenced from:
      _luaopen_module in module-fb0b1f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see  invocation)

C 模块本身:

#include "lua.h"

static int super(lua_State* L) {
    lua_pushnumber(L, 5);
    return 1;
}

int luaopen_module(lua_State* L) {
    lua_register(L, "super", super);
    return 0;
}

我的 Lua 脚本:

require("module")
print(super())

我在基于 Unix 的系统(Mac)上,但我也希望它可以在 Linux 上运行。

编辑:

通过输入 -bundle -undefined dynamic_lookup 替换 -shared(感谢 lhf),解决了编译 C 模块的问题,但我无法在 Lua 中导入模块。

> require("module")
error loading module 'module' from file './module.so':
    dynamic libraries not enabled; check your Lua installation

另外一件事情: 这似乎只是一个快速的修复;-bundle -undefined dynamic_lookup。这在 Linux 上不起作用。我想在基于 Unix 的系统上找到解决方案。

点赞
用户107090
用户107090
  • lua.org 下载 Lua 并使用 make macosx 编译 Lua。参见 入门指南

  • 使用 -bundle -undefined dynamic_lookup 代替 -shared 来构建 module.so

  • 使用 require"module" 将其加载到 Lua 中。

  • 调用 super

请确保您运行的是上述编译好的 lua 程序,而不是其他安装的版本。

2016-11-28 11:23:44