如何使用Lua构建C程序

test.c:

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main(){

  lua_State *L = luaL_newState();  /* opens Lua */
  luaL_openlibs(L);   /* opens the standard libraries */

  luaL_dofile(L,"test.lua"); /* runs Lua scrip */

  lua_close(L);
  return 0;

}

build:

gcc -o test test.c -I/usr/local/Cellar/lua/5.1.5/include

然后我得到了以下错误:

test.c:7:18: warning: implicit declaration of function 'luaL_newState' is
      invalid in C99 [-Wimplicit-function-declaration]
  lua_State *L = luaL_newState();  /* opens Lua */
                 ^
test.c:7:14: warning: incompatible integer to pointer conversion initializing
      'lua_State *' (aka 'struct lua_State *') with an expression of type 'int'
      [-Wint-conversion]
  lua_State *L = luaL_newState();  /* opens Lua */
             ^   ~~~~~~~~~~~~~~~
2 warnings generated.
Undefined symbols for architecture x86_64:
  "_luaL_loadfile", referenced from:
      _main in test-dxPwkn.o
  "_luaL_newState", referenced from:
      _main in test-dxPwkn.o
  "_luaL_openlibs", referenced from:
      _main in test-dxPwkn.o
  "_lua_close", referenced from:
      _main in test-dxPwkn.o
  "_lua_pcall", referenced from:
      _main in test-dxPwkn.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我通过 Homebrew 安装了 Lua:

ls /usr/local/Cellar/lua/5.1.5/include
lauxlib.h lua.h     lua.hpp   luaconf.h lualib.h

有谁知道如何解决这个错误吗?谢谢。

点赞
用户2203643
用户2203643

当您编译时,您需要使用 ld 命令链接 lua.so 文件(可能在 /usr/local/lib),找到它,并使用 -L 添加库的路径,使用 -l 链接库。

最后,在编译完成后,如果程序无法运行,您还应该使用 ln -s 命令创建一个符号链接,该链接与 /usr/lib 中的 .so 文件相关联。

2013-12-08 06:55:51
用户107090
用户107090

这是 luaL_newstate,而不是 luaL_newState

你还需要在命令行的末尾加上 -llua -lm

2013-12-08 11:32:23