Search code examples
c++linkerluajit

How to link LuaJIT with a C++ program?


I'm trying to simply use the following C++ code

lua_State *state = luaL_newstate();

luaL_openlibs(state);

lua_getglobal(state, "_G");
lua_pushstring(state, "print");
lua_pushnumber(state, 4.5);
lua_call(state, 2, 1);

lua_close(state);

And I'm getting linker errors. All of the aforementioned function calls generate linker errors:

1>main.obj : error LNK2001: unresolved external symbol _luaL_newstate
1>main.obj : error LNK2001: unresolved external symbol _lua_pushnumber
1>main.obj : error LNK2001: unresolved external symbol _lua_call
1>main.obj : error LNK2001: unresolved external symbol _lua_pushstring
1>main.obj : error LNK2001: unresolved external symbol _luaL_openlibs
1>main.obj : error LNK2001: unresolved external symbol _lua_getfield
1>main.obj : error LNK2001: unresolved external symbol _lua_close

The header inclusion is done with this code :

extern "C" {
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"
}

I "installed" LuaJIT using MinGW, mingw32-make BUILDMODE=static. It gave me a nice "Successfully built LuaJIT".

I'm compiling the code with VS2012. I've set up the linker like this :

Additional Library Directiories : D:\Programming\LuaJIT Source\LuaJIT-2.0.1\src Additional Include Directiories : D:\Programming\LuaJIT Source\LuaJIT-2.0.1\src

I'm on a windows7 machine and I'm using the latest LuaJIT from their github page.


Solution

  • In general, you should compile all your libraries using the same compiler as your application. MinGW produces a .a library archive whereas MSVC typically outputs a .lib archive.

    So: Recompile LuaJIT using MSVC, add the path where luajit.lib resides to your linker path and add luajit.lib to the list of libraries to be linked into your application.