ewok
ewok

Reputation: 21453

problems embedding lua in c++

I am attempting to embed lua code in C++, and I'm getting a strange compiler error. Here's my code:

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

int main() {
    lua_State *luaVM = luaL_newstate();
    if (luaVM == NULL) {
        printf("Error initializing lua!\n");
        return -1;
    }

    luaL_openlibs(luaVM);

    luaL_dofile(luaVM, "test.lua");

    lua_close(luaVM);

    return 0;
}

compiled with:

g++ -Wall -o embed -llua embed.cpp

and the error is:

g++ -Wall -o embed -llua embed.cpp
/tmp/ccMGuzal.o: In function `main':
embed.cpp:(.text+0x47): undefined reference to `luaL_loadfilex'
embed.cpp:(.text+0x72): undefined reference to `lua_pcallk'
collect2: error: ld returned 1 exit status

I am not calling luaL_loadfilex or lua_pcallk from my code, which lends itself to the assumption that the problem is not in my code, but in lua itself. does anyone have any ideas here?

UPDATE

Here is my version info:

$ lua -v
Lua 5.2.0  Copyright (C) 1994-2011 Lua.org, PUC-Rio

Upvotes: 2

Views: 2697

Answers (4)

Andres Riofrio
Andres Riofrio

Reputation: 86

You can use:

cc embed.cpp -o embed -llua -L../lua -I../lua -lm -ldl

Upvotes: 0

ewok
ewok

Reputation: 21453

Ultimately the problem was that the libraries are named differently by version. When installed from the repository, the libraries are called liblua5.x and liblualib5.x, and therefore the following command was required:

g++ -Wall -o embed embed.cpp -llua5.2 -llualib5.2

Upvotes: 2

Shahbaz
Shahbaz

Reputation: 47513

Pre 5.1 answer: According to this website, you need to add -llualib after -llua if you include lauxlib.h and lualib.h:

g++ -Wall -o embed embed.cpp -llua -llualib

Update

Silly me, you should always link files/libs in the order they use the other. If A uses B, you should mention A before B.

In your case, since embed.cpp uses lua, then you should write:

g++ -Wall -o embed embed.cpp -llua

Upvotes: 2

yuri kilochek
yuri kilochek

Reputation: 13486

In in lua 5.2.1 luaL_dofile is a macro that is declared like so:

#define luaL_dofile(L, fn) \
    (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))

in your version of lua it might very well be implemented with luaL_loadfilex and lua_pcallk, and you get undefined references like @Shahbaz said.

Upvotes: 2

Related Questions