David
David

Reputation: 733

How to fix this error I get while attempting to execute a Lua file via C++?

I'm trying to execute a Lua file using C++.

I'm running Mac OS X and Lua 5.3 is located in /usr/local/include

When I try to execute the Lua file, I get the following error:

Undefined symbols for architecture x86_64:
  "lua_settop(lua_State*, int)", referenced from:
      _main in lual-8d0dcd.o
  "luaopen_base(lua_State*)", referenced from:
      main::lualibs in lual-8d0dcd.o
  "luaL_newstate()", referenced from:
      _main in lual-8d0dcd.o
  "lua_close(lua_State*)", referenced from:
      _main in lual-8d0dcd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This is the C++ file:

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main(int argc, char* argv[]) {

    lua_State *lua_state;
    lua_state = luaL_newstate();

    static const luaL_Reg lualibs[] = {
        { "base", luaopen_base },
        { NULL, NULL}
    };

    const luaL_Reg *lib = lualibs;
    for(; lib->func != NULL; lib++) {
        lib->func(lua_state);
        lua_settop(lua_state, 0);
    }

    luaL_dofile(lua_state, "helloworld.lua");

    lua_close(lua_state);

    return 0;
}

Can anybody help me?

Thanks.

Upvotes: 1

Views: 655

Answers (1)

mniip
mniip

Reputation: 796

You need to add an extern "C" block around your includes:

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

The reason for this is that Lua is written in C, and therefore exports functions the "C way" by simply using the function name as symbol name. Your C++ program expects the symbols to be named the "C++ way" which includes encoded type information. The extern "C" block forces C-style symbol naming.

As @ChrisBeck suggests, you can just add Lua sources into your project, and compile them as if they were C++. Then the functions would be exported with C++-style names.

Upvotes: 3

Related Questions