gpt4 book ai didi

c++ - 不能在 C++ 中使用 lua 库

转载 作者:太空狗 更新时间:2023-10-29 23:01:27 27 4
gpt4 key购买 nike

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

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

它起作用了:当我在命令行中调用 lua 时,它显示了版本,lua 5.3.1;然后,我使用这个 lua 库编写了一个简单的 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 输出 -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':

我做错了什么?

最佳答案

readme 中所述, make linux 在Lua src 目录下(或者在顶层目录下)生成三个文件: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 重建它。

关于c++ - 不能在 C++ 中使用 lua 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31111891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com