1

I define a function In a Lua Script and call it from my C++ program. The Lua Script use cjson module. I can executes the Lua script by Lua bin, but it can't run in my C++ program. Error Message:

error loading module 'cjson' from file '/usr/local/app/cswuyg/test_lua/install/cjson.so': /usr/local/app/cswuyg/test_lua/install/cjson.so: undefined symbol: lua_getfield

cpp code:

    extern "C"
{
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

void test_dostring(lua_State* L, const std::string& file_path) {
    std::ifstream ifs;    
    ifs.open(file_path.c_str());
    if (!ifs.is_open()) {
        return ;
    }
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    std::string file_info(buffer.str());
    // test luaL_dostring
    std::cout << luaL_dostring(L, file_info.c_str()) << std::endl;
    std::cout << "error msg:" << lua_tostring(L, -1) << std::endl;
    lua_getglobal(L, "comment2");
    lua_pushstring(L, "xxx");
    lua_call(L, 1, 0);
    std::string lua_ret = lua_tostring(L, -1);
    std::cout << "ret:" << lua_ret << std::endl;
}

int main(int argc, char* argv[]) {
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    test_dostring(L, "test.lua");
    lua_close(L);
    return 0;
}

Lua code:

local Json = require('cjson')
function comment2(test)
    print(test)
end
comment2("xx")

How to fix it ? Any help would be appreciated.

cswuyg
  • 56
  • 5
  • Can you check if the library actually exposes the symbols required, e.g. by `nm -gC json.so`? – Stephan Lechner Jun 09 '17 at 09:48
  • @StephanLechner cjson.so is fine, it can be use by lua bin. – cswuyg Jun 09 '17 at 11:09
  • If the Lua core library is linked statically into your program, you need to expose it by using -Wl,-E when you build your program. (I'm guessing you're using Linux.) – lhf Jun 09 '17 at 11:22
  • @lhf thank you, it works. But why? my test program export lua* function can be use for cjson.so? – cswuyg Jun 09 '17 at 13:12

1 Answers1

1

If you're using Linux and the Lua core library is linked statically into your program, you need to expose the Lua C API by using -Wl,-E when you build your program. That's the incantation used to build the Lua command line interpreter from lua.org.

lhf
  • 70,581
  • 9
  • 108
  • 149