• 关于c调用lua 对‘luaL_newstate()’未定义的引用的问题解决办法


    #include <string.h>#include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"

    int main(int argc, char *argv[])
    {
        char buff[256];
        int error;
        lua_State *L = luaL_newstate();
        luaL_openlibs(L);

        while (fgets(buff, sizeof(buff), stdin) != NULL) {
            error = luaL_loadbuffer(L, buff, strlen(buff),
                                    "line") || lua_pcall(L, 0, 0, 0);
            if (error) {
                fprintf(stderr, "%s", lua_tostring(L, -1));
                lua_pop(L, 1);/* pop error message from the stack */
            }
        }
        lua_close(L);
        return 0;
    }

    最近学习lua脚本,编译上面程序一直如下错误 用g++ a.cpp -o a -llua -ldl

    [root@localhost lua+c]# g++ a.cpp -o a -llua -ldl
    a.cpp:8: 警告:不建议使用从字符串常量到‘char*’的转换
    /tmp/ccij5HeF.o:在函数‘main’中:
    a.cpp:(.text+0xe):对‘luaL_newstate()’未定义的引用
    a.cpp:(.text+0x24):对‘luaL_openlibs(lua_State*)’未定义的引用
    a.cpp:(.text+0x60):对‘luaL_loadbufferx(lua_State*, char const*, unsigned int, char const*, char const*)’未定义的引用
    a.cpp:(.text+0x9b):对‘lua_pcallk(lua_State*, int, int, int, int, int (*)(lua_State*, int, int))’未定义的引用
    a.cpp:(.text+0xe4):对‘lua_tolstring(lua_State*, int, unsigned int*)’未定义的引用
    a.cpp:(.text+0x107):对‘lua_settop(lua_State*, int)’未定义的引用
    a.cpp:(.text+0x140):对‘lua_close(lua_State*)’未定义的引用

    网上查的说法都是库没有链接成功,折腾了好久,最后在http://blog.csdn.NET/zuijinbuzai/article/details/7385380中找到了答案,

    原来是因为lua是C语言模块,用g++调用c语言的库需要在包含头文件时加上extern "C",就能正常编译了,即修改为

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

    #include <string.h>

    int main(int argc, char *argv[])
    {
        char buff[256];
        int error;
        lua_State *L = luaL_newstate();
        luaL_openlibs(L);

        while (fgets(buff, sizeof(buff), stdin) != NULL) {
            error = luaL_loadbuffer(L, buff, strlen(buff),
                                    "line") || lua_pcall(L, 0, 0, 0);
            if (error) {
                fprintf(stderr, "%s", lua_tostring(L, -1));
                lua_pop(L, 1);/* pop error message from the stack */
            }
        }
        lua_close(L);
        return 0;
    }

  • 相关阅读:
    Leetcode总结之Tree
    Leetcode总结之DFS
    Leetcode总结之Backtracking
    策略模式(设计模式_02)
    面向对象思想设计_计算器小程序(设计模式入门篇_01)
    Android GridView 滑动条设置一直显示状态
    dp暑假专题 训练记录
    dp入门 专题记录 2017-7-26
    dp问题 -挑战例题 2017-7-24
    贪心思维 专题记录 2017-7-21
  • 原文地址:https://www.cnblogs.com/daochong/p/7308610.html
Copyright © 2020-2023  润新知