簡體   English   中英

無法使用 liblua.a (lua5.3) 編譯的 C 程序加載 C 動態庫

[英]Cannot Load C dynamic library with C Program compile with liblua.a (lua5.3)

我首先下載 lua-5.3.5 ,並將源代碼放在我的工作目錄中並使用

make linux

所以我在 ./lua-5.3.5/src 中得到了 liblua.a 和 lua 二進制文件。

然后我寫了一個這樣的 C 動態庫:

#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <stdlib.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

static int l_sin(lua_State *L) 
{   
    double d = luaL_checknumber(L, 1); 
    lua_pushnumber(L, sin(d));  /* push result */

    return 1;  /* number of results */
}


static const struct luaL_Reg mylib[] = { 
    {"mysin", l_sin},
    {NULL, NULL}
};

extern int luaopen_mylib(lua_State* L)
{
    luaL_newlib(L, mylib);

    return 1;
}

我用命令編譯:

gcc mylib.c -I ./lua-5.3.5/src -fPIC -shared -o mylib.so -Wall

如果我使用原始的 lua 二進制文件,它可以被加載

user00:lua/ $ ./lua-5.3.5/src/lua                                                                                                                                                                    
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> require 'mylib'
table: 0xd13170
> 

但是如果我寫一個鏈接liblua.a的AC程序,它就不能加載動態庫。

#include <stdio.h>
#include <string.h>

#include "lua.h"           
#include "lauxlib.h"       
#include "lualib.h"

int main(void){
    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);
        }
    }

    lua_close(L);
    return 0;
}

編譯:

gcc test01.c -L ./lua-5.3.5/src/ -llua -lstdc++ -o test01 -lm -ldl -I ./lua-5.3.5/src

跑:

user00:lua/ $ ./test01                                                                                                         
require 'mylib'
error loading module 'mylib' from file './mylib.so':
    ./mylib.so: undefined symbol: luaL_setfuncs

您需要從可執行文件中導出 Lua API 函數。 為此,將它與 -Wl,-E 鏈接,就像 Lua 發行版中的 Makefile 所做的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM