Lua 5.3 未定义的引用。

我正在尝试学习如何在 C 程序中嵌入 lua,但我不擅长阅读技术文档,也没有找到任何现有的教程。这是我的程序:

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

void report_errors(lua_State*, int);

int main(int argc, char** argv) {
    for (int n = 1; n < argc; ++n) {
        const char* file = argv[n];
        lua_State *L = luaL_newstate();

        luaL_openlibs(L);

        std::cerr << "-- Loading File: " << file << std::endl;

        int s = luaL_loadfile(L, file);

        if (s == 0) {
            s = lua_pcall(L, 0, LUA_MULTRET, 0);
        }

        report_errors(L, s);
        lua_close(L);
        std::cerr << std::endl;
    }
    return 0;
}

void report_errors(lua_State *L, int status) {
    if (status) {
        std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
        lua_pop(L, 1);
    }
}

编译器为 luaL_newstate、luaL_openlibs、luaL_loadfilex、lua_pcallk 和 lua_close 给出未定义引用错误。我正在使用 Windows 计算机上的 Code::Blocks,并将 Lua 包含目录添加到所有搜索路径和 liblua53.a 添加到链接库。IDE 自动完成了头文件名称,解析器显示了大多数 lua 函数,但是进行了简短的搜索后,我发现解析器无法找到 lua_newstate 或 luaL_newstate。为什么它可以找到一些函数而不能找到其他函数?

点赞
用户1890567
用户1890567

在C++中,你应该包含lua.hpp而不是lua.hlua.h没有定义extern"C"块来阻止c++编译器的名称修饰。

2015-05-06 19:05:30
用户2526216
用户2526216
The arguments for g++ had -llua before the input file. I put -llua at the end, and everything works fine now.

g++ 命令的参数在输入文件之前是包含了 -llua。我把 -llua 放到最后面,现在一切正常运行。

2015-05-20 18:23:53
用户6164083
用户6164083

出现 undefined reference to `luaL_newstate' 错误时,需要加上 extern "C" 包裹,并且按照上面的建议,在最后加上 "-llua"。

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

gcc -o l -ldl l.cpp -llua5.3

2022-06-10 20:02:43