编译一个简单的C lua5.0程序,未定义的引用

时间:2019-03-29 11:31:32

标签: c lua linker-errors dynamic-linking

我尝试编译此简单的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找不到上述功能? 有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分: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中的函数,则可能不会加载这些函数。

相关问题