c++clualinker

Lua 5.2: undefined symbols when using luaL_dofile()


I was trying to do some simple Lua 5.2 embedding using the following C++ code:

void dnLuaRunner::Exec(string file)
{
    // Initialize the lua interpreter.
    lua_State * L;
    L = luaL_newstate();

    // Load lua libraries.
    static const luaL_Reg luaLibs[] =
    {
        {"math", luaopen_math},
        {"base", luaopen_base},
        {NULL, NULL}
    };

    // Loop through all the functions in the array of library functions
    // and load them into the interpreter instance.
    const luaL_Reg * lib = luaLibs;
    for (; lib->func != NULL; lib++)
    {
        lib->func(L);
        lua_settop(L, 0);
    }

    // Run the file through the interpreter instance.
    luaL_dofile(L, file.c_str());

    // Free memory allocated by the interpreter instance.
    lua_close(L);
}

The first part is some basic initialization and code for loading some standard library modules, but when I called luaL_dofile(...) it seemed to be raising some errors for undefined symbols. luaL_dofile is a macro that uses functions like luaL_loadfile and lua_pcall, so it didn't look extremely scary that I was getting the following linker errors:

  "_luaL_loadfilex", referenced from:
      dnLuaRunner::Exec(std::string) in dnLuaRunner.cc.o
  "_lua_pcallk", referenced from:
      dnLuaRunner::Exec(std::string) in dnLuaRunner.cc.o
ld: symbol(s) not found for architecture x86_64

I was linking liblua.a correctly in the Makefile.


Solution

  • Turns out you need to add -lm along with -llua and they both must be after the file you want to compile, like so:

    # or clang++ works too
    $ g++ ... foofy.c -llua -lm
    

    I have also seen circumstances where you must use -ldl at the end as well.