如何构建包含Lua的C程序

我正在学习如何将Lua嵌入C中,并从一个简单的例子开始:

demo.c

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main (void) {
    char buff[256];
    int error;
    lua_State *L = luaL_newstate();   /* opens Lua */
    luaopen_base(L);             /* opens the basic library */
    luaopen_table(L);            /* opens the table library */
    luaopen_io(L);               /* opens the I/O library */
    luaopen_string(L);           /* opens the string lib. */
    luaopen_math(L);             /* opens the math lib. */

    while (fgets(buff, sizeof(buff), stdin) != NULL) {
        error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
            lua_pcall(L, 0, 0, 0);
        if (error) {
            fprintf(stderr, "%s", lua_tostring(L, -1));
            lua_pop(L, 1);  /* pop error message from the stack */
        }
    }

    lua_close(L);
    return 0;
}

======

我的本地环境:

evans@master:~/codebase/demo/lua$ sudo dpkg -L liblua5.2-dev
/.
/usr
/usr/include
/usr/include/lua5.2
/usr/include/lua5.2/lua.h
/usr/include/lua5.2/luaconf.h
/usr/include/lua5.2/lualib.h
/usr/include/lua5.2/lauxlib.h
/usr/include/lua5.2/lua.hpp
/usr/lib
/usr/lib/i386-linux-gnu
/usr/lib/i386-linux-gnu/liblua5.2.a
/usr/lib/i386-linux-gnu/pkgconfig
/usr/lib/i386-linux-gnu/pkgconfig/lua5.2.pc
/usr/share
/usr/share/doc
/usr/share/doc/liblua5.2-dev
/usr/share/doc/liblua5.2-dev/copyright
/usr/lib/i386-linux-gnu/liblua5.2.so

然后:

gcc -o demo demo.c -llua5.2
demo.c:3:17: fatal error: lua.h: No such file or directory
compilation terminated.

我也尝试了-llua5-llua,但全部失败。

====== 最后我找到了一个解决方案:

gcc -o demo demo.c -I/usr/include/lua5.2 /usr/lib/i386-linux-gnu/liblua5.2.a -lm

但我无法弄清为什么我不能像平常一样做。

点赞
用户88888888
用户88888888

你需要指定 header 文件的实际路径:

#include <lua5.2/lua.h>

或者像你已经发现的那样使用 -I/usr/include/lua5.2。当你尝试包含 <lua.h> 时,编译器只会在 /usr/include/lua.h(以及其他一些不重要的地方)中查找它。

2013-05-20 04:24:37
用户3020040
用户3020040

将所有位于/usr/include/lua*.*的文件复制到/usr/include/目录下。

2016-03-18 21:28:50