不能在C++中使用lua库

Cannot use lua libraries in C++

本文关键字:lua C++ 不能      更新时间:2023-10-16

好的,所以我尝试在linux/Ubuuntu上编译一个简单的C++lua程序;首先,我安装了lua-libs:我下载了lua源代码,并自己编译成这样:

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

它起作用了:当我在命令林中调用lua时,它向我显示了lua 5.3.1的版本;然后,我用这个lua-lib:编写了一个简单的C++程序

#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;
}

但当我这样编译它时:g++ test.cpp -o output -llua

我得到以下错误:

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':

我做错了什么?

如自述中所述,Lua src目录(或顶级目录)中的make linux生成三个文件:lua(解释器)、luac(编译器)和liblua.a(库)。

lua(翻译)是一个普通的Lua客户,和你的一样。make linux显示的构建线为:

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

注意存在-ldl。还要注意-Wl,-E,它允许在lua(解释器)加载动态C库时解析Lua API符号。如果您计划用程序加载动态C库,请使用-Wl,-E重新构建它。