Gcc 无法用liblua.a(lua5.3)编译的C程序加载C动态库
我首先下载lua-5.3.5,将源代码放在我的工作目录中,并使用Gcc 无法用liblua.a(lua5.3)编译的C程序加载C动态库,gcc,lua,dynamic-library,lua-5.3,lua-c++-connection,Gcc,Lua,Dynamic Library,Lua 5.3,Lua C++ Connection,我首先下载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" #incl
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;
}
如果我使用原始的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链接的C程序,它将无法加载动态库
#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;
}
运行:
您需要从可执行文件中导出luaapi函数。为此,请像Lua发行版中的Makefile那样将其链接到-Wl,-E。谢谢,它可以工作gcc test01.c-L./lua-5.3.5/src/-llua-lstdc++-o test01-lm-ldl-I./lua-5.3.5/src-Wl-E`
#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