Can't use lua libraries in C ++

Ok, so I tried to compile a simple C ++ lua program on linux / Ubuntu; Firt, I installed the lua libs: I downloaded the lua sources and compiled it like this:

`sudo make linux install` /// in the `lua src` directory

      

It worked: when I called lua on the command line, it showed me the version, lua 5.3.1; Then I wrote a simple C ++ program using this lua lib:

#include <stdio.h>

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

/* the Lua interpreter */
lua_State* L;

static int average(lua_State *L)
{
    /* get number of arguments */
    int n = lua_gettop(L);
    double sum = 0;
    int i;

    /* loop through each argument */
    for (i = 1; i <= n; i++)
    {
        /* total the arguments */
        sum += lua_tonumber(L, i);
    }

    /* push the average */
    lua_pushnumber(L, sum / n);

    /* push the sum */
    lua_pushnumber(L, sum);

    /* return the number of results */
    return 2;
}

int main ( int argc, char *argv[] )
{
    /* initialize Lua */
    L = luaL_newstate();

    /* load Lua base libraries */
    luaL_openlibs(L);

    /* register our function */
    lua_register(L, "average", average);

    /* run the script */
    luaL_dofile(L, "avg.lua");

    /* cleanup Lua */
    lua_close(L);

    /* pause */
    printf( "Press enter to exit..." );
    getchar();

    return 0;
}

      

But when I compile it like this:  g++ test.cpp -o output -llua

I am getting the following error:

loadlib.c:(.text+0x502): undefined reference to `dlsym'
loadlib.c:(.text+0x549): undefined reference to `dlerror'
loadlib.c:(.text+0x576): undefined reference to `dlopen'
loadlib.c:(.text+0x5ed): undefined reference to `dlerror'
//usr/local/lib/liblua.a(loadlib.o): In function `gctm':

      

What am I doing wrong?

+3


source to share


1 answer


As mentioned in the readme , make linux

in the Lua directory src

(or top level directory) produces three files: lua

(interpreter), luac

(compiler) and liblua.a

(library).

lua

(interpreter) is a regular Lua client just like yours. The build line shown make linux

for it:



gcc -std=gnu99 -o lua lua.o liblua.a -lm -Wl,-E -ldl -lreadline 

      

Please note the availability -ldl

. Also note that -Wl,-E

this allows the Lua API to resolve symbols when lua

(the interpreter) loads C dynamic libraries. If you plan to load C dynamic libraries with your program, then rebuild it with -Wl,-E

.

+1


source







All Articles