简体   繁体   中英

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

I first download lua-5.3.5 , and put the source in my working directory and compile it with

make linux

so I got the liblua.a and lua binary file in ./lua-5.3.5/src.

And then I write a C Dynamic Library like this :

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

I compile with command :

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

And if I use the original lua binary, it can be loaded

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

But If I write AC program linked with liblua.a, it cannot load the dynamic library.

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

Compile :

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

Run:

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

You need to export the Lua API functions from your executable. For this, link it with -Wl,-E as the Makefile from the Lua distribution does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM