使用mingw构建和编译lua 5.3.3时出现 undefined reference 错误

所以我得到了lua5.3.3源代码,尝试使用mingw构建它

我到目前为止所做的是在msys中完成整个操作,然后将lib文件、bin文件和include文件复制到mingw适当的文件夹中

但是,当我尝试编译一个使用它的应用程序时,我会遇到以下错误

这是我编译使用lua的程序时使用的命令

gcc syx.cpp -llua

C:\Users\User\AppData\Local\Temp\cckJPF8N.o:syx.cpp:(.text+0xf): undefined reference to `luaL_newstate()'
C:\Users\User\AppData\Local\Temp\cckJPF8N.o:syx.cpp:(.text+0x21): undefined reference to `luaL_openlibs(lua_State*)'
C:\Users\User\AppData\Local\Temp\cckJPF8N.o:syx.cpp:(.text+0x3e): undefined reference to `luaL_loadfilex(lua_State*, char const*, char const*)'
C:\Users\User\AppData\Local\Temp\cckJPF8N.o:syx.cpp:(.text+0x77): undefined reference to `lua_pcallk(lua_State*, int, int, int, int, int (*)(lua_State*, int, int))'
C:\Users\User\AppData\Local\Temp\cckJPF8N.o:syx.cpp:(.text+0x87): undefined reference to `lua_close(lua_State*)'
collect2.exe: error: ld returned 1 exit status

如果需要,以下是该文件(非常基本)

#include <stdio.h>

#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>

/* Lua解释器 */
lua_State* L;

int main ( int argc, char *argv[] )
{
   L = luaL_newstate();

   luaL_openlibs(L);

   luaL_dofile(L, "test.lua");

   /* 清理Lua */
   lua_close(L);

        return 0;
}

我知道库文件存在,因为它是使用mingw创建的,即liblua.a位于我的mingw lib文件夹中,以及其他Lua相关文件,如lua.exe luac.exe include文件等,所以我不确定缺少什么。

点赞
用户7358334
用户7358334

好的,我找到了解决方法。

结果发现gcc在库头文件中搞乱了符号(不知道是什么意思)。

需要做的是把头文件包裹在extern "C" { //headers }中才能使其工作。

参考链接在这里:

http://www.linuxquestions.org/questions/programming-9/undefined-reference-error-when-using-lua-api-892782/

为了更清楚,这里有一个可以工作的示例:

#include <stdio.h>

extern "C"{
#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
}

/* Lua解释器 */
lua_State* L;

int main ( int argc, char *argv[] )
{
   L = luaL_newstate();

   luaL_openlibs(L);

   luaL_dofile(L, "test.lua");

   /* 清理Lua */
   lua_close(L);

        return 0;
}
2017-01-20 15:48:00