编译一个简单的C lua5.0程序,未定义的参考文献[重复]

问题描述 投票:2回答:1

我尝试编译这个简单的Lua教程程序:

#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 = lua_open();   /* opens Lua */
      luaopen_base(L);             /* opens the basic library */
      luaopen_table(L);            /* opens the table library */
      luaopen_io(L);               /* opens the I/O library */
      luaopen_string(L);           /* opens the string lib. */
      luaopen_math(L);             /* opens the math lib. */

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

使用以下命令:

gcc -I/usr/include/lua50 -L/usr/lib/liblua50.a -llua50 luainterpret.c

所以标题是链接的,图书馆二进制文件也应链接好吗?

但是我得到以下未定义的参考文献:

/tmp/ccA3kOUt.o: In function `main':
luainterpret.c:(.text+0x1b): undefined reference to `lua_open'
luainterpret.c:(.text+0x31): undefined reference to `luaopen_base'
luainterpret.c:(.text+0x40): undefined reference to `luaopen_table'
luainterpret.c:(.text+0x4f): undefined reference to `luaopen_io'
luainterpret.c:(.text+0x5e): undefined reference to `luaopen_string'
luainterpret.c:(.text+0x6d): undefined reference to `luaopen_math'
luainterpret.c:(.text+0xa1): undefined reference to `luaL_loadbuffer'
luainterpret.c:(.text+0xc3): undefined reference to `lua_pcall'
luainterpret.c:(.text+0xf6): undefined reference to `lua_tostring'
luainterpret.c:(.text+0x11f): undefined reference to `lua_settop'
luainterpret.c:(.text+0x152): undefined reference to `lua_close'
collect2: error: ld returned 1 exit status

我用nm检查了/usr/lib/liblua50.a文件,上面的函数确实存在!为什么gcc然后无法找到所述函数?谁能告诉我我做错了什么?

c lua linker-errors dynamic-linking
1个回答
2
投票

而不是将库放在源文件之前(使用库中存在的函数),尝试将其放在后面,比如

gcc -I/usr/include/lua50 -L/usr/lib/liblua50.a  luainterpret.c -llua50

来自online gcc manual

它在您编写此选项的命令中有所不同;链接器按照指定的顺序搜索和处理库和目标文件。因此,foo.o -lz bar.o在文件z之后但在foo.o之前搜索库bar.o。如果bar.o引用z中的函数,则可能无法加载这些函数。

© www.soinside.com 2019 - 2024. All rights reserved.