mingw 或 msys2 用 gcc 编译 lua

在 Windows 操作系统上喜欢使用 msys2 (mingw32 已经很久不更新了),具体我用的 msys2 中的 mingw64 ,下面的测试都是在 mingw64 上测试的。使用的 lua 是 5.2.4 版本。

其实发现在 mingw 上编写 c 库拓展 lua 是那么简单方便,就像这篇博客一样简单。lua 脚本可以在运行时加载 c 库,但要求编译 c 库时用的 lua 库是动态库。好消息是编译 lua 时的 mingw 选项就会产生动态 lua 库。这样就可以直接编译并使用了。

编译 lua 。进入目录 cd lua-5.2.4 然后编译 make mingw 。

编译之后会在 lua-5.2.4/src 目录下产生 lua52.dll 。不要被名字搞混了,有这个文件就足够了。将文件复制一份并改名为 liblua52.dll.a 。

这样就生成了动态 lua 库,编译 c 库时用 liblua52.dll.a 而在运行时用 lua52.dll 。将 lua52.dll 丢到 mingw 的 bin 目录下,将 liblua52.dll.a 丢到 mingw 的 lib 目录下。运行时在 mingw 的 bash 上运行,就不需要修改环境变量而可以直接运行。编译时使用选项 -llua52.dll 即可。

很简单吧。发现网上那些的博客似乎没有这么简单的,就顺手记录了一下:)

下面来写个简单的小例子来测试一下。就是编写一个 c 库,可以获取 lua 传递的字符串中字符的个数。由于例子很简单,目的只是为了感受下流程,下面就直接贴代码了。

新建文件 strlib.c 加入如下代码。

include <lua/lauxlib.h>

include <lua/lualib.h>

static int

l_num(lua_State *L) {

size_t l = 0;

luaL_checklstring(L, 1, &l);

lua_pushinteger(L, l);

return 1;

}

static const struct luaL_Reg libs[] = {

{"num", l_num},

{NULL, NULL},

};

int

luaopen_strlib(lua_State *L) {

luaL_newlib(L, libs);

return 1;

}

新建文件 strtest.lua 加入如下代码,用于测试 c 库。

package.cpath = "./?.dll;./?.so"

local s = require("strlib")

print("the num of char of s:", s.num("hello!")) -- 6

可以使用上面使用 mingw 选项编译 lua 时生成的 lua.exe 解释器(注意,静态编译生成的解释器运行不了)运行 strtest.lua 。也可以自己写一个简单的解释器运行。代码如下。

include <lua/lua.h>

include <lua/lauxlib.h>

include <lua/lualib.h>

include <stdio.h>

include <string.h>

int

main() {

char buff[1024];

int error;

lua_State *L = luaL_newstate();

luaL_openlibs(L);
while (1) {
        fprintf(stdout, "please enter lua code:\n"); fflush(stdout);
        fgets(buff, sizeof(buff), stdin);
        if (strcmp(buff, "exit\n") == 0)
                break;
        error = luaL_loadstring(L, buff) || lua_pcall(L, 0, 0, 0);
        if (error) {
                fprintf(stdout, "error:%s\n", lua_tostring(L, -1)); fflush(stdout);
                lua_pop(L, 1);
        }
}

fprintf(stdout, "exit now\n");
lua_close(L);
return 0;

}

Makefile 文件如下。

COMMON = -g -Wall -I. -llua52.dll

all: strbin strlib

strbin:

gcc -o ./\(@ ./\)@.c \((COMMON) strlib: gcc -shared -o ./\)@.so ./$@.c $(COMMON)

一切准备就绪,可以编译并运行。

$ make

$ ./strbin

please enter lua code:

dofile("strtest.lua")

the num of char of s: 6

please enter lua code:

exit

exit now

或者使用 lua.exe 解释器。

$ make

lua strtest.lua